繁体   English   中英

使用Handlebars.js时如何将模板js外包到不同的文件

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

我有这个模板脚本

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

我想将它外包给一个名为“user_template.js”的文件,它看起来像这样:

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

并在主index.html中建立此链接:

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

问题是 - 它不起作用 - 我该怎么办?

我会使用RequireJS 使用模块非常可爱,还有一个名为text的插件,可以与模板一起使用。

如果听起来很有趣,这里有一些链接:

http://requirejs.org/

http://requirejs.org/docs/download.html#text - 文本插件

RequireJS仅适用于您想使用模块的情况,如果不是Alon的答案更好。

您可以使用ajax加载模板文件。

使用jQuery:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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