Search code examples
javascriptjquerybackbone.jsmustache

jquery templating - import a file?


I'm working with backbone.js, but as far as I've seen, it doesn't care what templating system you use. Currently I'm trying out mustache.js, but I'm open to other ones. I'm a little annoyed though with the way I have to put a template into a string:

var context = {
    name: this.model.get('name'),
    email: this.model.get('email')
}

var template = "<form>Name<input name='name' type='text' value='{{name}}' />Email<input name='email' type='text' value='{{email}}' /></form>";

var html = Mustache.to_html(template, context);
    $(this.el).html(html);
    $('#app').html(this.el);

I'd like if I could load it from a different file or something somehow. I want to be able to have template files in order to simplify things. For example, if I put it all in a string, I can't have breaks (well I can have html breaks, but that's not the point). After the line starts to get very long, it becomes unmanageable.

Tips?


Solution

  • Updated (4/11/14):

    As answered by OP below:

    Unfortunately, the jQuery team has moved the templating functionality out of jQuery Core. The code is still available as a library here: github.com/BorisMoore/jquery-tmpl and here: github.com/borismoore/jsrender

    Original Answer:

    I just used this a couple of hours ago: http://api.jquery.com/category/plugins/templates/

    It's an official jQuery plugin(i.e. the devs endorse it).

    This is the function you need to use for loading templates from things other than strings: http://api.jquery.com/template/

    Here's the code to have a template in HTML:

    <script id="titleTemplate" type="text/x-jquery-tmpl">
      <li>${Name}</li>
    </script>
    ___________
    
    // Compile the inline template as a named template
    $( "#titleTemplate" ).template( "summaryTemplate" );
    
    function renderList() {
      // Render the movies data using the named template: "summaryTemplate"
      $.tmpl( "summaryTemplate", movies ).appendTo( "#moviesList" );
    }
    

    It's in a <script> tag, because that's not visible by default.
    Note the type="text/x-jquery-tmpl". If you omit that, it will try to parse it as JavaScript(and fail horribly).

    Also note that "loading from a different file" is essentially the same as "reading a file" and then "loading from a string".