Loading templates with backbone js

流过昼夜 提交于 2020-01-12 14:01:33

问题


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


回答1:


I would recommend using require.js with text plugin. Mixing html templates as strings in javascript variable is bad idea, as well as using something like <script type="text/template"></script>.

Here is one very good series on backbone.js which covers template loading and project build as well: http://dailyjs.com/2012/11/29/backbone-tutorial-1/. Github project is also provided there.




回答2:


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?



来源:https://stackoverflow.com/questions/14097535/loading-templates-with-backbone-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!