cor*_*vid 27 javascript jquery backbone.js underscore.js
我试图创建一个基本的应用程序,使用主干,下划线和Parse.
在我的index.html中,我尝试包含一些这样的脚本:
<script data-main="js/main" src="../bower_components/requirejs/require.js"></script>
<script type="text/template" id="login-template" src="js/templates/login.js">
Run Code Online (Sandbox Code Playgroud)
当我尝试在我的骨干部分上执行以下操作时,它不起作用.
template: _.template($('#login-template').html());
// ...
render: function() {
this.$el.html(this.template());
}
Run Code Online (Sandbox Code Playgroud)
但是,当我更改我的脚本并将其直接添加到html文档中时,它运行正常.
<script type="text/template" id="login-template">
<header id="header"></header>
<div class="login">
<form class="login-form">
<h2>Log In</h2>
<div class="error" style="display:none"></div>
<input type="text" id="login-username" placeholder="Username" />
<input type="password" id="login-password" placeholder="Password" />
<button>Log In</button>
</form>
</script>
Run Code Online (Sandbox Code Playgroud)
为什么是这样?有没有办法在<script>标签中包含外部源的模板?
(我不能$.get用于这种情况,因为它不应该立即使用Web服务器并且不断正常地执行XHR错误.)
joe*_*ews 32
该<script>标签的src属性会导致浏览器做了一个HTTP请求login.js.但是,它不会将响应插入DOM.您需要这样才能使代码生效.
浏览器不这样做的原因很简单,因为HTML5规范没有说明它们应该这样做.
特别是,脚本规范包含用户代理在准备<script>标记和执行其源时必须采取的操作的列表.这些列表不指示浏览器将脚本的源插入DOM.内联方法有效,因为脚本源已经在DOM中.
您可以通过检查<script>具有src属性的任何标记来查看此行为- 在加载,解析和执行其源之后,它将不包含子节点.
您可以使用AJAX请求加载模板,但不推荐 - 如果您的应用程序具有少量模板,则只需将它们包含在主HTML文件中即可; 如果它有几个你需要很多服务器往返来获取它们.
最好的解决方案通常是构建步骤,将模板编译为JavaScript文件中的单个Object,可以像任何其他脚本一样包含它.
通过这样的步骤将模板编译为一个名为的变量AppTemplates,您的代码将类似于:
template: AppTemplates['templates/login.tpl']
Run Code Online (Sandbox Code Playgroud)
Grunt有一个名为grunt-contrib-jst的任务,可以为Underscore.js模板执行此操作.其他模板引擎有相同的任务.