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?
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.
If you are using logicless client-side template engine like Transparency templates can be embedded in main HTML because the templates themselves are valid HTML.
Example:
<!-- Template -->
<div id="template">
<span class="greeting"></span>
<span class="name"></span>
</div>
// Data
var hello = {
greeting: 'Hello',
name: 'world!'
};
<!-- Result -->
<div id="template">
<span class="greeting">Hello</span>
<span class="name">world!</span>
</div>
For templates to be used in widget like manner a hidden <div>
container does fine.
Putting HTML'ish code to Javascript codeblocks and Javascript strings is ugly and should be avoided if possible. It is not syntax highlightable and you miss errors easily.
I greatly prefer the second option, for the following reasons:
But using the second option requires loading your template file somehow, or including it in your HTML, or sticking it into your HTML at build time. Plus there's more data overhead due to the script
tag, AND you have to get the string from the DOM using jQuery's .html()
or a similar method. So performance-wise, the string option might be better - which is why @Matt's suggestion of putting it into strings at build time is probably best.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With