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

Alo*_*lon 5 html javascript jquery mvvm handlebars.js

我有这个模板脚本

<script id="some-template" type="text/x-handlebars-template">
   {{#users}}
     {username}
     {email}
</script>
Run Code Online (Sandbox Code Playgroud)

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

   {{#users}}
     {username}
     {email}
Run Code Online (Sandbox Code Playgroud)

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

<script id="some-template" type="text/x-handlebars-template" src="user_template.js"></script>
Run Code Online (Sandbox Code Playgroud)

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

won*_*ng2 3

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

使用 jQuery:

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