Ember.js带有外部车把模板

Ember.js with external handlebars template

本文关键字:外部 js Ember      更新时间:2023-09-26

所以,我对Ember.js有点陌生,自从我被困住以来已经有几个小时了。我正在使用这个 bloggr 客户端,我想完成的是从外部文件加载这些handlebars模板。

当用户单击面板中的关于页面时,"关于"模板应呈现。简而言之,这是代码,因此您不必挖掘那么多(我相信对于有经验的用户来说会很容易)

里面的模板。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"的脚本元素,并调用编译其内容。 然后,它将结果添加到具有数据模板名称属性名称的Ember.TEMPLATES对象。 这可能会给应用程序增加一些完全不必要的加载时间。

例如,当我们发送"I'm a cow {{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 中,这样您就可以避免花时间编译模板客户端。