Skip to content

Grunt & Angular's template.

2015-04-22 22:07:09

When we build AngularJS application, we create plenty of html files that contains for example directive's template or partials use with ng-include.

It is great from development perspective. Because we can manage easier our code base, but for browser perspective it can be hard work to make request for each file.

That is why you should consider combining that files with index.html (I assume that this is your start point for your AngularJS app).

AngularJS provide that possibility by:

<script id='"---URL---"' type='"text/ng-template"'></script>

where id is the url that your directive or ng-include use to take file form server, if you add something like this, AngularJS will take html form that script/tpl blok instead of calling server for that html part. It is great !

But storing all html code in one html file is a recipe for mess and chaos (from development process perspective).

Ok, but we can automate it by Grunt

You can work with all files separately and have Grunt task to prepare version for production.

Awesome !

How to do that ?

You have to install grunt-inline-angular-templates

npm install grunt-inline-angular-templates --save-dev

Next, you have to configure grunt task

inline_angular_templates: {
    dist: {
        options: {
            unescape: {
                '&amp;lt;': '&lt;',
                '&amp;gt;': '&gt;',
                '&amp;apos;': '\'',
                '&amp;amp;': '&amp;'
        files: {
            'index_prod.html': [

What does it mean ? All html files storaged in 'app/views/*/.html' will be added to index_prod.html. Of course you have to have this file.

As a result you will see something like this:

<!-- Begin Templates -->

<script id='"app/views/ipsum.part.html"' type='"text/ng-template"'>
<h1>Ipsum Box</h1>

<script id='"app/views/lorem.part.html"' type='"text/ng-template"'>
<h1>Lorem box</h1>

<!-- End Templates -->

Of course as you know this is not everything what Grun can do for you. On my github you can find working example, with that flow: - remove production file - run javascript validator - compress & combines javascript file - preeper index_prod.html - add angular tamplates to index_prod.html