How to use an HTML minifier with underscore templates

I have some templates for my frontend code, like:

<div class="row">
    <div class="my-header col-md-1">
        <!-- comments -->
        {{ title }}
    </div>
    <div class="my-container col-md-11">
    {% if (content) { %}
        {{ content }}
    {% } else { %}
       <p>Empty</p> 
    {% } %}
    </div>
</div>

And I'm using grunt-contrib-jst to store them all in a single file and then on another build step will be included in a single JS file and that file is pushed to the CDN. This part is working perfectly, but I want to use the processContent option to minify the HTML template code, which contains Undercore template delimiters ( <%...%> replaced with {% ... %} , <%= ... %> replaced with {{ ... }} ).

I wanted to use html-minifier but it doesn't actually minimize anything, apparently because it tries to parse the template as HTML-only (and fails because of the templating tags).

Is there any Node package / function that allows me to minimize this kind of templates? I would like to use comments and whitespace in source templates but strip everything unnecessary on the resulting build file.

Right now I have this on my JST settings:

processContent: function (content) {
    return content
        .replace(/^[x20t]+/mg, '')
        .replace(/[x20t]+$/mg, '')
        .replace(/^[rn]+/, '')
        .replace(/[rn]*$/, 'n');
},
...

But I want to minimize everything possible, that's why I tried with html-minifier.

Thanks!


I can't really help with minimising the underscore template delimiters, still trying to find out the best way to do that myself, but you might want to consider running your templates through htmlclean. I use it with r.js and it works really well for stripping out newlines and spaces in the code. Example usage:

var htmlclean = require('htmlclean');

// ...
processContent: function (content) {
    return htmlclean(content)
        .replace(/^[x20t]+/mg, '')
        .replace(/[x20t]+$/mg, '')
        .replace(/^[rn]+/, '')
        .replace(/[rn]*$/, 'n');
},

I've had no problems with using this on HTML that has underscore templates in there. I hope it helps you.

链接地址: http://www.djcxy.com/p/20640.html

上一篇: GHC运行时如何处理文件I / O?

下一篇: 如何使用HTML缩小器和下划线模板