Hacker News new | ask | show | jobs
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!

1 comments

I have a class called Tag with static methods for all relevant tag names which merely wraps $('<' + tagname + '/>') and thus allow for stuff like:

   Tag.ul(
       Tag.li('unclickable li tag')
           .addClass('unclickable'),
       Tag.li('test clickable li tag')
           .addClass('clickable')
           .click(function() {
               alert('clicked on test')}))
I prefer this as it keeps my view code "in language" and makes it easy to apply any sort of jquery methods which I need to the different elements.