javascriptunderscore.jsseparation-of-concernsclient-side-templating

Place client-side JavaScript templates in HTML or JavaScript?


Should client-side templates like the following (using underscore's templating engine):

<p class="foo"><%= bar %></p>

be placed in an separate HTML file, or a separate JavaScript file? I know it could work both ways.

For example, a JavaScript file could just contain a list of string variables like so:

var cute = '<p class="the"><%= unicorn %></p>';
var fb   = '<p class="new-design"><%= sucks %></p>';

But I have also seen the following:

<script type="text/template" id="omg-template">
  <span id="swag-name"><%= name %></span>
</script>

Just from a Separation of Concerns standpoint, where does the template storage belong?


Solution

  • I usually will use an asset management system that concatenate and minify javascripts and css, and translate client side template files into JS strings hanging off a global var. This sort of thing depends on your platform, but in the rails world you want to look at jammit or sprockets (which is now part of rails)

    If I don't have decent asset management, I will usually end up using the script tag method, with the templates split out into partials on the server, and included into the bottom of the page. It is sort of a pain to work with, but IMO anything more then your simple example string templates really shouldn't exist inline in your javascript file.