如何在空格键中访问标签属性



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

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

您无法直接从空格键模板访问标签属性。您需要为此创建一个模板帮助程序。

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

然后你像这样使用它:

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

更新:为了使帮助程序在窗口调整大小事件上重新计算,您需要对其进行一些修改。为此,可以使用依赖项对象。

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

经过一些研究,我发现没有空格键正确的解决方案,最好的选择是使用 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"); } });
}

最新更新