Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grunt-contrib-htmlmin how to ignore template tags

I'm using grunt-contrib-htmlmin to minify my html in a backbone/underscorejs project, however, when I run grunt-contrib-htmlmin on any underscorejs template that has <%= myvar %>, the task outputs a parse error. Is there a way grunt-contrib-htmlmin can ignore text inside <%= and %>?

like image 883
wwwuser Avatar asked Nov 19 '13 19:11

wwwuser


2 Answers

Since you posted this issue, an new feature was introduced into html-minifier (which is used by grunt-contrib-htmlmin) to ignore the interpolation tags that were causing the problem.

For instance, the following html partial:

<div>
    <span><%= variable %></span>
</div>

Will now minify to:

<div><span><%= variable %></span></div>

Before the changes, it would have resulted in an error.

You can try this using the demo on the website to test it out. If that works, you can update your project to make use of the new version.

like image 160
mckramer Avatar answered Nov 02 '22 12:11

mckramer


This issue is old but grunt-contrib-htmlmin and html-minifier can take new options.

As already mentioned by @mckramer, grunt-contrib-htmlmin sits on top of html-minifier so you are able to add additional options:

customAttrAssign:<value>

Arrays of regex'es that allow to support custom attribute assign expressions

customAttrSurround:<value>

Arrays of regex'es that allow to support custom attribute surround expressions

The solution

Example grunt configuration (for double braces {{ }}):

var hbAttrWrapOpen = /\{\{(#|\^)[^}]+\}\}/;
var hbAttrWrapClose = /\{\{\/[^}]+\}\}/;
var hbAttrWrapPair = [hbAttrWrapOpen, hbAttrWrapClose];

htmlmin: {
  blabla: {
    options: {
      ...
      customAttrSurround: [hbAttrWrapPair]
    },
    files: [
      ...
    ]
  }
}

These are the only limitations according to the documentation:

...

Note that these expressions are used for parsing individual attribute+value pairs, so a single Handlebars expression may not span multiple attributes. For example, the following markup would not be recognized:

<img src="logo.svg" {{#if logo_title}}alt="{{logo_title}}" title="{{logo_title}}"{{/if}} />

Instead, each attribute must be individually wrapped:

<img src="logo.svg" {{#if logo_title}}alt="{{logo_title}}"{{/if}} {{#if logo_title}}title="{{logo_title}}"{{/if}} />

That's it, just you keep an eye on your markup and it will work without issues.

like image 3
mate64 Avatar answered Nov 02 '22 10:11

mate64