How to outsource a template js to a different file when using Handlebars.js

半腔热情 提交于 2019-12-18 04:22:17

问题


I have this template script

<script id="some-template" type="text/x-handlebars-template">
   {{#users}}
     {username}
     {email}
</script>

I want to out-source it to a file called "user_template.js" which will look like this:

   {{#users}}
     {username}
     {email}

and make in the main index.html this link:

<script id="some-template" type="text/x-handlebars-template" src="user_template.js"></script>

The problem is - it doesn't work - how do I do it?


回答1:


You can use ajax to load the template file.

With jQuery:

$.get("user_template.js", function(template_text){
    var template = Handlebars.compile(template_text);
    // more things
});



回答2:


I would use RequireJS for this. Lovely to work with modules and there is also a plugin that is called text that works beautifully with templates.

If it sounds interesting, here's some links:

http://requirejs.org/

http://requirejs.org/docs/download.html#text -- The text plugin

RequireJS is only suitable if you want to use modules though, if not Alon's answer is better.



来源:https://stackoverflow.com/questions/12035839/how-to-outsource-a-template-js-to-a-different-file-when-using-handlebars-js

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