Loading templates with backbone js

10,731

Require is a good option from the ones you listed.

Is there a reason you haven't considered simply:

  1. Storing templates in the pages that use them as <script type='text/template'> nodes?

  2. Storing templates as text (non-JS) files and loading them via XHR on pages that use them?

Share:
10,731
Goofyahead
Author by

Goofyahead

Updated on June 04, 2022

Comments

  • Goofyahead
    Goofyahead almost 2 years

    I'm starting in javascript development, and did a simple project with node.js as a rest API and a client using backbone, everything look perfectly till I want to get my templates out of my js.

    I found different approaches, some of them with some time (like one year old) but I can't understand which one could be better:

    • A .js file with a var with the html code

      pros -> easy to load, easy to pass to underscore to compile it.

      cons -> scape every single line.

      app.templates.view = " \
      <h3>something code</h3> \
      ";
      

      load template:

      template: _.template(app.templates.view)
      

    External template in Underscore

    • Use require.js to load with text plug-in.

      pros -> load different templates as needed.

      cons -> I don't like the approach to put everything inside a "loader" function...

      define(["TemplateEngine", "text!templates/template.html"], function(...
      

    RequireJS: Loading modules including templates and CSS

    • A function that loads the templates with an AJAX petition.

      pros -> You can load the template that you need and adds local storage posibilities.

      cons -> Seems that I have to merge all my templates into one file for production environments.

      function() {
      
      var templateLoader = {... $.get calls ...}   
      

    Best way to asynchronously load underscore templates

    • And a Jquery plug-in for template loading that I really liked but it seems that it didn't go to release?

    http://api.jquery.com/jQuery.template/

    It seems that require is the best approach, but maybe I'm missing something, I do wan't to make things as clean as possible since I'm in the learning/having fun phase :D

    Any good article or github project with a good structure or any light on this will be appreciated.

    Thanks.

    Excuse any major spelling mistake, not an English speaker :)

    --EDIT-- found some interesting videos to understand how to start and wrap things with require.js http://www.youtube.com/watch?v=VGlDR1QiV3A

    http://www.youtube.com/watch?v=M-wjQjsryMY