grunt-contrib-htmlmin how to ignore template tags

天大地大妈咪最大 提交于 2019-12-30 18:50:36

问题


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 %>?


回答1:


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.




回答2:


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.




回答3:


Same workaround, except with regexps for Jekyll tags:

var jekyllConditionalWrapOpen = /\{\% if[^}]+\%\}/;
var jekyllConditionalWrapClose = /\{\%[^}]+endif \%\}/;
var jekyllConditionalWrapPair = [jekyllConditionalWrapOpen, jekyllConditionalWrapClose];


来源:https://stackoverflow.com/questions/20080853/grunt-contrib-htmlmin-how-to-ignore-template-tags

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!