Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(/^[\x20\t]+/mg, '')
        .replace(/[\x20\t]+$/mg, '')
        .replace(/^[\r\n]+/, '')
        .replace(/[\r\n]*$/, '\n');
},
...

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

Thanks!

like image 638
Armando Pérez Marqués Avatar asked May 19 '14 20:05

Armando Pérez Marqués


1 Answers

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(/^[\x20\t]+/mg, '')
        .replace(/[\x20\t]+$/mg, '')
        .replace(/^[\r\n]+/, '')
        .replace(/[\r\n]*$/, '\n');
},

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

like image 180
Ben Avatar answered Nov 15 '22 00:11

Ben