如何访问空格键中的标记属性

时间:2016-07-08 11:53:48

标签: meteor spacebars

如何从标签中获取属性值,如宽度,颜色,值......

<template>
   {{#if body.width > 979px }}
      {{> tmp1 }}
   {{else}}
      {{> tmp2 }}
   {{/if}}
</template>

<template name="tmp1">...</template>
<template name="tmp2">...</template>

2 个答案:

答案 0 :(得分:0)

您无法直接从Spacebars模板访问标记属性。您需要为此创建一个模板助手。

Template.templateXY.helpers({
   bigBody: function() {
      return $("body").width() > 979;
   }
});

然后你就像这样使用它:

<template name="templateXY">
   {{#if bigBody}}
      {{> tmp1}}
   {{else}}
      {{> tmp2}}
   {{/if}}
</template>

UPDATE :要让帮助程序重新计算窗口大小调整事件,您需要稍微修改一下。您可以使用Dependency对象。

Template.templateXY.onCreated(function() {
   // create a dependency
   this.resizeDep = new Dependency();
});

Template.templateXY.onRendered(function() {
   let tmpl = this;
   // invalidate the dependency on resize event (every 200ms)
   $(window).on("resize.myEvent", _.throttle(function() {
      tmpl.resizeDep.changed();
   }, 200));
});

Template.templateXY.helpers({
   bigBody: function() {
      // recompute when the dependency changes
      Template.instance().resizeDep.depend();
      return $("body").width() > 979;
   }
})

Template.templateXY.onDestroyed(function() {
   $(window).unbind("resize.myEvent");
});

其他可能的解决方案是将窗口宽度存储到ReactiveVar(这是一个反应性数据源本身)并使用.on(“resize”,fn)来更改ReactiveVar

答案 1 :(得分:0)

经过一些研究,我发现没有空格键正确的解决方案,最好的选择是使用js代码。

所以这是代码:

Session.set("width", $(window).innerWidth());
window.onresize = function () { Session.set("width", $(window).innerWidth()); };

if(Meteor.isClient) {
    Template.body.helpers({ 'dynamicTemplateName': function () { return Session.get("width"); } });
}