|
|
|
|
|
by Pewpewarrows
5493 days ago
|
|
Not Backbone itself, but its dependency written by the same (awesome) developers: Underscore.js. Underscore has functions to help you with client-side templating. It basically boils down to you writing html as you normally would within a script tag, like so: <script id="foobar" type="text/html">
<ul>
<li><%= test %></li>
</ul>
</script>
Because it's in a script tag, the browser doesn't render that snippet of a template on its own. And since the type is text/html, the browser also doesn't try to interpret that as javascript. Now all you have to do is select the id of the script tag using your favorite library (like jQuery) or with getElementById, get the innerHtml as a string, and pass it to Underscore's template function along with a dictionary of values that you want replaced (such as test above). Like Django or Rails templates, you also can do some basic logic within the template, like looping over an array to make a list of items.If Underscore's syntax isn't your cup of tea, there's a slew of other libraries available, like Mustache or jQuery's own tmpl module. You'll never go back to building the DOM yourself or dozens of concatenated strings of html again! |
|