use one large external file for many javascript templates with backbone.js?

ぐ巨炮叔叔 提交于 2020-01-01 16:42:09

问题


I have two different HTML pages that serve up backbone apps. Up until now, I have put all the js templates inside of each respective HTML file.

Now, I'm refactoring a bit and would like to share some backbone views between files. When loading a view that can't find a js template, the whole app will error out. I know the proper way to merge these two would be to have external js templates, using EJS for example, and have 1 template per file, however, I'd like to just have one huge HTML file with embedded <script type='text/template'> and share the template HTML file between my 2 pages. Is this possible? I tried getting the external js templates with AJAX and writing them to the head, but backbone views still can't find them.

Does anyone else choose to have a file with many javascript templates in it? I also find that I have an unmanageable number of files open when I use ejs. Any help would be most appreciated.


回答1:


I use an extra javascript/coffeescript file and use underscore's templating to take care of everything. This way you can include the templates and put them into as few (or many) files as you would like.




回答2:


I'm using a single file for all the templates on my current project and it is working out pretty well.

It's a Asp.Net site, so I made the template file into a user control so I can easily include it in any page that uses Backbone.




回答3:


If you're fetching all templates through AJAX, maybe you don't have to write them to the head.

You can send templates to the client as JSON Object, for example:

{"about":"<p>About</p>...","gallery":"<p>Gallery</p>...","contact":"<p>Contact</p>..."}

After fetching temples you can store them as templates variable inside some object(or locale storage), and after that you can do the following:

var tempStr = templates['about'],
    template = new EJS({element:{value: tempStr, id: 'about'}}),
    content = template.render();


来源:https://stackoverflow.com/questions/8594295/use-one-large-external-file-for-many-javascript-templates-with-backbone-js

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