正如在任何项目中预期的那样,我的主HTML文件的90%由许多不同的模板组成,就像这样:
<script type="text/template" id="template-parametros">
<div id="parametros">
<h2>Parâmetros</h2>
<table id="tab-parametros">
<tr><td>Descrição</td><td>Tipo</td><td>Locale</td></tr>
</table>
<button id="parametros-ad">Adicionar</button>
</div>
</script>我想把它们放在其他地方,这样UX的人就可以自己工作了。将它们放到另一个文件中很容易,但我如何在以后导入它们?我尝试过,但是浏览器试图将其解释为javascript代码,当然,失败了。type="text“也失败。有什么想法吗?
谢谢!
发布于 2012-08-16 09:29:56
我使用一个模块加载器(requireJS),它有一个文本插件。它允许您将模板文件定义为参数,并在Backbone View中使用。
带有require的Backbone视图看起来像这样。
define([
'jquery',
'underscore',
'backbone',
'text!/templates/templateFileName.html' // Define the template using text! plugin
], function($, _, Backbone, myTemplate) { // Include the template as an argument
"use strict";
ViewName = Backbone.View.extend({
template: _.template(myTemplate), // Setup my template (underscore)
events: {
...
},
initialize: function() {
...
},
render: function() {
$(this.el).html(this.template()); // render the template
return this;
}
});
return ViewName;
});为了补充这一点,使用下划线的_.template()很容易插入值。
假设我的templateFileName.html看起来像这样
<section>
<div>
<%= name %>
</div>
<div>
<%= age %>
</div>
</section>您所要做的就是传入带有这些属性名称的散列,以填充html。
var myHash = {"name":"Felix", "age":"9"};
$(this.el).html(this.template(myHash));发布于 2012-08-17 09:29:46
这样如何:
if (!async) async = false;
$.ajax({
async: async,
url: '/template/' + templateId,
dataType: 'json',
success: function(response) {
$('body').append(response.content);
}
});https://stackoverflow.com/questions/11977617
复制相似问题