访问Meteor中的父助手 [英] Accessing parent helper in Meteor

查看:66
本文介绍了访问Meteor中的父助手的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常发现自己将我的工作划分为仍然可以使用相同助手的模板。

I often find myself dividing my work into templates that still could use the same helpers.

所以,说我有这个模板结构:

So, say I have this template structure:

<template name="MainTemplate">
  <div>{{> FirstTemplate}}</div>
  <div>{{> SecondTemplate}}</div>
  <div>{{> ThirdTemplate}}</div>
  <div>{{> FourthTemplate}}</div>
</template>

现在每个模板都想使用同一个帮助器,我们称之为 dataHelper

Now each of these templates wants to use the same helper, let's call it dataHelper:

Template.MainTemplate.helpers({
  dataHelper: function() {
    //do some stuff
    return result
  }
})

可悲的是,只需输入 {{dataHelper}} 就可以在第一到第四个模板中访问此帮助程序,就像事件的工作方式一样。

Sadly, this helper can't be accessed in template first through fourth by simply typing {{dataHelper}} like how events work.

我的解决方案是创建一个全局帮助器,但这似乎有点矫枉过正,特别是因为我有一些页面根本不关心这些帮助器。另一个解决方案是创建四个独立的助手,但是,嘿,DRY。

My solution has been to create a global helper instead, but that seems a tad overkill, especially since I have a few pages that don't care about these helpers at all. Another solution is to create four separate helpers but, hey, DRY.

我在这里错过了一些简单的东西吗?

Am I missing something simple here?

推荐答案

在当前版本的流星中没有明显的方法可以做到这一点。一种解决方案是让子模板从父级继承帮助程序。您可以使用 meteor-template-extension 轻松完成此操作。以下是一个例子:

There isn't an obvious way to do this in the current version of meteor. One solution is for the child template to "inherit" the helpers from the parent. You can do this pretty easily using meteor-template-extension. Here's an example:

<body>
  {{> parent}}
</body>

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

<template name="child">
  <h2>child</h2>
  <p>{{saySomething}}</p>
</template>



js



js

Template.parent.helpers({
  saySomething: function() {
    return Random.choice(['hello', 'dude!', 'i know right?']);
  }
});

Template.child.inheritsHelpersFrom('parent');

模板 child 继承其所有父项帮助者所以它可以直接访问 saySomething

The template child inherits all of its parent's helpers so it has direct access to saySomething.

这种技术有两个缺点:


  • 您必须指定 inheritsHelpersFrom 关系

  • 所有

这篇关于访问Meteor中的父助手的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆