JavaScript templates

I was trying to convince a colleague to use Mustache / Hogan in the project interface and I suggested the following:

Having a templates.js file that might look something like this:

var tpl_alert = '<div class="alert">{{msg}}</div>';
var tpl_welcome = '<p class="user-{{type}}">Welcome, {{name}}</p>';
...

      

Then we will include templates.js and use the corresponding tpl in Mustache / Hogan.js rendering.

My offer was rejected as we are hard-coding html templates in js variables. Is it really that bad? What other alternatives to this?

+3


source to share


2 answers


To answer your question, placing templates in javascript variables inside a static JavaScript file makes it difficult to store your templates. You need to worry about line erasure when you want to make a simple change. And 1 syntax error will crash your application.

However, putting all your templates in one JavaScript file is the fastest way to load your templates.



Your alternatives:

  • Saving your templates in separate files and creating a static template.js file as a pre-build step.
  • Loading html files of async templates via AJAX into javascript variables.
  • Using a library like Require.js will load your templates asynchronously as needed into variables.
+2


source


My preferred way of doing this is to create a separate template file that can be dynamically loaded into development and baked into pure js for production.

In particular, I use eco templates (I would not recommend them if you are not familiar with coffee script) and Stitch for node.js . Stitch supports custom engines tied to file extensions, so when it finds an eco file in my project directory, it compiles it into a Javascript function. Now I can include this functionality in any other part of my application using the stitch function provided by the function require

using the original eco file path. So if the template was in src/views/listItem.eco

, I would run var listItemView = require('views/listItem');

to extract it and use it like this



var html = listItemView({item: items[i]});
$someElement.html(html);

      

You can use require.js instead of stitch if course or any other similar structure.

+1


source







All Articles