简体   繁体   中英

crunching templates in backbone.js

I'm using backbone.js and during development have many .js and .html template files (one per model). I'm crunching all the .js to one file before I deploy the app and it works great. How can I do this for the templates too? I've had a few ideas but they have problems:

  • put all templates under invisible "div" tags in the main page. however the templates will be "executed" once the browser loads them (eg pictures get download w/o need)
  • put the encoded templates inside javascript variables. But the encoded html will not be readable which is important for client debugging
  • put the templates in an external xml file. I want to avoid xml parser though. and other non-xml format will again not be readable due to encoding.

ok... I couldn't find anything before, but the moment after I published the question I learned about this:

<script type="text/template" id="user-template">
...
</script>

I recommend using handlebars for templating.

What I do is pack the templates into one javascript file (templates.js), so they are not on the DOM. The templates are compiled into js variables for production, but for development they are used as is so debugging should be simple.

I've written more about this on a blog post

on my project i do this as follows:

Backbone has Underscore in it and Underscore has already a very cool minimalistic Template system. so i write the templates in separate files and get them with jQuery

    $.get('html_template.tpl', function(template) {
        $(body).html(_.template(template)(template_data));
    });

so i let the user only download templates if really needed.

Maybe it helps.


Underscore Template : http://documentcloud.github.com/underscore/#template

如果您刚刚了解了<script type="text/template" id=""> ,则可以尝试ICanHaz.js ,或者可以尝试使用Handlebars.js

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM