[英]Ember.js with external handlebars template
所以,我对Ember.js
来说是个Ember.js
,自从我坚持这个以来已经有几个小时了。 我正在玩这个博客客户端 ,我想要完成的是从外部文件加载这些handlebars
模板。
当用户单击面板中的about页面时,应该呈现“about”模板。 这里是简短的代码,所以你不必挖掘那么多(我相信对于有经验的用户来说这很容易)
里面的模板。 html
如示例中所示
<script type="text/x-handlebars" id="about">
<div class='about'>
<p>Some text to be shown when users click ABOUT.</p>
</div>
现在我所做的是将x-handlebar
代码从html
页面移开并放置它(没有<script type...>
)然后将它放在hbs/about.hbs
现在,在html页面中我做了类似的事情。
$.ajax({
url: 'hbs/about.hbs',
async: false,
success: function (resp) {
App.About = Ember.View.extend({
template: Ember.Handlebars.compile(resp),
});
}
});
ajax的结果保存.hbs页面的内容,然后我必须编译它,所以Ember
可以渲染它,对吧? 认为这就是我所做的。 但就我而言,这就是我的意思。 我做得对吗? 下一步是什么? 我相信我必须将ajax调用的内容附加到body
左右。
提前谢谢,搜索完SO后我仍然无法让它运行。
您可以将模板附加到可用模板的对象,就像这样:
Ember.TEMPLATES.cow = Ember.Handlebars.compile("I'm a cow {{log this}}");
或者在你的情况下可能是这样的:
var url = 'hbs/about.hbs',
templateName = url.replace('.hbs', '');
Ember.$.ajax({
url: url,
async: false,
success: function (resp) {
Em.TEMPLATES[templateName] = Ember.Handlebars.compile(resp);
}
});
这是一个在应用程序就绪中完成的懒惰示例:
http://emberjs.jsbin.com/apIRef/1/edit
老实说,事先预先编译模板(服务器端)对最终用户来说更具性能。
预编译采用原始把手并将其转换为大量的javascript语句,以便在构建视图时使用。
当DOM准备就绪时,Ember会扫描DOM以查找“text / x-handlebars”类型的脚本元素,并对其内容调用compile。 然后,它将结果添加到Ember.TEMPLATES
对象,其名称来自data-template-name属性。 这可以为应用程序添加一些完全不必要的加载时间。
例如,当我们发送“我是奶牛{{log this}}”时,它被转换为以下javascript方法
function anonymous(Handlebars,depth0,helpers,partials,data /**/) {
this.compilerInfo = [4,'>= 1.0.0'];
helpers = this.merge(helpers, Ember.Handlebars.helpers); data = data || {};
var buffer = '', hashTypes, hashContexts, escapeExpression=this.escapeExpression;
data.buffer.push("I'm a cow ");
hashTypes = {};
hashContexts = {};
data.buffer.push(escapeExpression(helpers.log.call(depth0, "", {hash:{},contexts:[depth0],types:["ID"],hashContexts:hashContexts,hashTypes:hashTypes,data:data})));
return buffer;
}
最小化到像这样丑陋的东西:
function anonymous(e,t,n,r,i){this.compilerInfo=[4,">= 1.0.0"];n=this.merge(n,Ember.Handlebars.helpers);i=i||{};var s="",o,u,a=this.escapeExpression;i.buffer.push("I'm a cow ");o={};u={};i.buffer.push(a(n.log.call(t,"",{hash:{},contexts:[t],types:["ID"],hashContexts:u,hashTypes:o,data:i})));return s}
根据您的后端的不同,您可以预先编译和捆绑模板,并将其发送到html中,这样您就可以避免花时间编译模板客户端。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.