davidchambers / string-format

JavaScript string formatting inspired by Python’s `str.format()`

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Crash when formatting a string containing CSS

julien1619 opened this issue · comments

Hi,

I have a problem when using this library with an email I try to format. My workflow is the following:
MJML email containing variable to be formatted -> Generated HTML email file with variable -> Just before sending it, I replace all variables using string-format.

This email contains some CSS code and more specifically, this: { width:100% !important; }. I think the new version of string-format interprets it wrongly and tries to apply a transformer, which is unknown, causing a complete crash of my node application.

For now, I will downgrade the library to keep it usable.

Here is a partial stack trace:

/opt/app/node_modules/string-format/index.js:53
    throw ValueError('no transformer named "' + xf + '"');

Thank you!

Could you provide more context, @julien1619?

Keep in mind is that because squiggly brackets have special meaning, literal { and } characters require escaping. For example:

> format('{{ width: {}% !important }}', 100)
'{ width: 100% !important }'

Here is a partial HTML that was working before, on 0.5.0, and that does not work anymore on 1.0.0. My HTML file is auto-generated during my build process, meaning that if I want to escape { and } I probably would end up coding a parser to find which character I have to escape or not, losing the benefit of this library for my specific use case.

<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office">
  <head>
    <title></title>
    <style type="text/css">
      @media only screen and (min-width:480px) {
        .mj-column-per-100 { width:100% !important; }
      }
    </style>
  </head>
  <body style="background-color:#f6f6f6;">
    <div>
      Hello <b>{name}</b>,
    </div>
  </body>
</html>

Note that even with v0.5.0 the unescaped squiggly brackets cause problems:

> require('string-format/package.json').version
'0.5.0'

> format('.mj-column-per-100 { width:100% !important; }', {name: 'Julien'})
'.mj-column-per-100 '
> require('string-format/package.json').version
'1.0.0'

> format('.mj-column-per-100 { width:100% !important; }', {name: 'Julien'})
ValueError: no transformer named "important; "

I suggest sticking with v0.5.0 for now. At some point you could consider moving to an HTML templating library, so you don't need to remember to escape special characters in each of your context variables.

Ok, I think you're right, maybe I should move to an HTML template library. I really hope to find one without any dependency just like yours, and it's rare enough to be underlined and supported ;) Thank you anyway!

Three cheers for projects without dependencies! 🎉