【问题标题】:Detect which template includes the current one in Meteor检测哪个模板包含 Meteor 中的当前模板
【发布时间】:2014-11-08 03:02:49
【问题描述】:

我想检测哪个模板包含另一个模板,因为我只想为一个特定模板创建一个 css 类。

这是它的工作原理:

<template name="includedTempl">    
      <div class="panel panel-default {{#if templateX}}specialCSS{{/if}}" id="{{_id}}">
</template>

Template.includedTempl.helpers({
    templateX: function() {
       if (this.includedBy('templX.html')) {
            return true;
       }
       return false;
    }
});

我该怎么做? 任何帮助将不胜感激。

【问题讨论】:

  • 似乎更简单的解决方案是另辟蹊径——将一些上下文从父模板传递给子模板,如果它是“你很特别”的话。例如{{&gt; includedTemplate special=true}}。如果您认为这可行,我可以添加一个答案来解释这个更详细。
  • 感谢您的帮助!那真是太棒了!

标签: javascript meteor


【解决方案1】:

一般而言,子模板确定其父上下文可能具有挑战性,因为它可能嵌套任意次数。因此,父母通常更容易为孩子提供触发所需行为的上下文。这是一个例子:

app.html

<body>
  {{> parentTemplate parentContext}}
</body>

<template name="parentTemplate">
  {{> childTemplate specialContext}}
  {{> childTemplate}}
</template>

<template name="childTemplate">
  <div class="{{isSpecialClass}}">
    <p>parent name: {{name}}</p>
  </div>
</template>

app.js

if (Meteor.isClient) {
  Template.body.helpers({
    // add some context to the parent do demo how it can be modified
    parentContext: {name: 'dave'}
  });

  Template.parentTemplate.helpers({
    specialContext: function () {
      // make a copy of the parent data context
      var data = _.clone(Template.instance().data || {});
      // modify the context to indicate the child is special
      data.isSpecial = true;
      return data;
    }
  });

  Template.childTemplate.helpers({
    isSpecialClass: function () {
      // grab the context for this child (note it can be undefined)
      var data = Template.instance().data;
      if (data && data.isSpecial)
        // add the 'awesome' class if this child is special
        return 'awesome';
    }
  });
}

这里,父模板创建了两个子模板。第一个孩子与isSpecial 一起被赋予了父上下文。带有isSpecial 的模板将包含带有awesome 类的div。唯一棘手的部分是父助手和子助手都必须使用Template.instance 来确定他们的上下文。

推荐阅读

【讨论】:

  • 谢谢!我认为这对我的情况来说是更好的解决方案。祝你有美好的一天!
  • 我只有一个问题。我注意到 this 现在是 { isSpecial: true } 而不是实际对象。我该如何更改?
  • 好问题 - 我修改了示例以展示如何扩展父上下文。它有点复杂,但希望能提供信息。
  • 对不起,但我认为它不起作用,我在这里创建了一个问题:stackoverflow.com/questions/26843042/…
  • 我的回答修改了父上下文而不是子上下文,我猜这就是你想要的。我将在另一个问题中给出另一个解决方案。
【解决方案2】:

您需要访问模板实例以获取父名称。

<template name="parent">
   {{> child }}
</template>

<template name="child">
   <p>
      My father is <b>{{ fatherTemplate abc=23 }}</b>
   </p>
</template>
Template.child.helpers({
  'fatherTemplate' : function(){
      return UI._templateInstance().view.parentView.name;
  }
});

Template.child.rendered = function(){
    console.log("Father Template name: ", this.view.parentView.name);
}

【讨论】:

  • 谢谢!但是,我必须使用 console.log(UI._templateInstance().view.parentView.parentView.parentView.parentView.name); 来获取我的模板名称。有没有更“动态”的方式?
  • 你可以递归地得到父母,直到你得到你想要的父母。根节点/父节点是“body”,使用 name 属性来检查。
猜你喜欢
  • 1970-01-01
  • 2011-03-23
  • 2012-08-15
  • 2014-05-14
  • 2014-11-22
  • 1970-01-01
  • 1970-01-01
  • 2015-08-31
  • 1970-01-01
相关资源
最近更新 更多