【问题标题】:Can you pass a dynamic variable into a Meteor blaze template?您可以将动态变量传递给 Meteor blaze 模板吗?
【发布时间】:2023-03-20 15:30:02
【问题描述】:

我看到了对这个 stackoverflow 帖子的回复:Is there a way to pass variables into templates in Meteor?

这篇文章只展示了如何将静态值传递给 blaze 模板。请参阅以下示例 - 我正在尝试将 user.username 传递到模板 cookieTemplate

<template name="userTemplate">
  <p> Wellcome {{user.username}} </p>
  {{#each user.profile.cookies}}
    {{> cookieTemplate username={{user.username}} }}
  {{/each}}
</template>

<template name="cookieTemplate">
  {{username}} has cookie {{this.cookieName}}
</template>

我知道我可以使用Session.set('username', blah) 来执行此操作,但我想知道是否可以将动态变量传递给模板?

【问题讨论】:

    标签: meteor meteor-blaze


    【解决方案1】:

    一个简单的解决方案就是将用户对象传递给模板

    {{> cookieTemplate user=user }}
    

    并在模板中使用它

    {{user.username}}
    

    或者您写下一些帮助程序来创建具有相关属性的数据对象,例如:

    Template.userTemplate.helpers({
      get_user: function() {
        return { username: Template.instance().user.username }
    }
    

    然后用

    调用模板
    {{> cookieTemplate user=get_user }}
    

    并使用该值

    {{user.username}}
    

    我为这个线程做了类似的东西(帮助函数)作为 MeteorPad Access an object's property names in a Blaze template

    也许对你有帮助

    干杯, 汤姆

    【讨论】:

      【解决方案2】:

      是的,您可以而且可能已经这样做了。

      一般来说,如果您通过自动发布或发布订阅获取数据,则数据被视为反应性数据。无论如何,每次集合有更新时,此更新都会推送到模板。

      对于您的情况,如果您通过currentUserMeteor.user() 获取数据,情况相同。

      【讨论】:

        猜你喜欢
        • 2015-09-30
        • 1970-01-01
        • 1970-01-01
        • 2015-09-22
        • 2016-05-21
        • 2020-02-02
        • 1970-01-01
        • 1970-01-01
        • 2019-02-02
        相关资源
        最近更新 更多