Ignacio
Ignacio

Reputation: 8035

JavaScript templating

I was trying to convince a fellow co-worker into using Mustache/Hogan in the front-end of a project and I proposed the following:

Having a templates.js file, which could roughly look like this:

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

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

My proposal was turned down, since we're hardcoding html templates into js variables. Is this really that bad? Which are other alternatives to this?

Upvotes: 3

Views: 1085

Answers (2)

dmck
dmck

Reputation: 7861

To answer your question, putting your templates in javascript variables inside a static JavaScript file makes it difficult to maintain your templates. You need to worry about string escaping whenever you want to make a simple change. And 1 syntax error will crash your app.

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

Your alternatives are:

  1. Storing your templates in seperate files and generating the static template.js file as a prebuild step.
  2. Loading your html template files async through AJAX into javascript variables.
  3. Using a library like Require.js that will load your templates asynchronously as needed into variables.

Upvotes: 2

Hubro
Hubro

Reputation: 59408

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

Specifically I use eco templates (I wouldn't recommend them unless you're 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. I can now include that function in any other part of my application using the stitch provided require function using the original path of the eco file. So if the template resided in src/views/listItem.eco I would run var listItemView = require('views/listItem'); to fetch it and use it like this

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

You could use require.js instead of stitch if course, or any other similar framework.

Upvotes: 1

Related Questions