从铁路由器访问模板中的数据上下文数据时出现问题

Trouble accessing data-context data in template from Iron Router

本文关键字:数据 上下文 问题 路由器 访问      更新时间:2023-09-26

我有一个模板,其中的数据通过这里的铁路由器参数传递到其中,模板的设计目的可能很明显:

lib/routes.js

// custom reset password page for child user
Router.route('/reset-password/child/:_id', {
    name: 'reset-child-password',
    template: 'childResetPassword',
    layoutTemplate: 'appLayout',
    data: function() {
        return Users.findOne({ _id: this.params._id });
    }
});

但是,当我尝试访问模板中的此子用户数据时,我收到错误,指出this.data未定义。 或cannot read property 'profile' of undefined .这是我的助手和帮助程序的模板使用。

client/templates/childResetPassword.html

<h3>Reset Password for {{childFirstName}}</h3>
        <form id='childResetPassword'>
          <div class="form-group">
            <input type="password" name="new-child-password" class="form-control" value=''>
          </div>

client/templates/helpers/childResetPassword.js

Template.childResetPassword.helpers({
    childFirstName: function() {
        console.log("Template helpers:");
        console.log(this.data);
        return this.data.profile.firstname;
    }
});

关于如何访问通过铁路由器数据回调传递的数据上下文的任何想法?我用错了吗?

更新(仍未回答):我已经验证了我正在传递到模板数据上下文中的这个特定用户正在被找到,并且他们的配置文件填充了 firstname 属性,但我仍然收到相同的错误。

根据我发现的另一个问题,我尝试了这个。我添加了一个模板渲染的回调函数,如下所示:

client/templates/helpers/childResetPassword.js

Template.childResetPassword.rendered = function() {
    console.log(this);
};

我确实在浏览器控制台中看到 this.data 包含正确的用户对象,但我的this.data.profile.firstname仍然再次失败,并出现相同的控制台输出错误。如果我需要在模板渲染和模板助手之间执行某些操作?太糊涂了

!!

你不必提到数据...你可以叫这个.profile.firstname。应用程序已将"this"理解为返回的数据对象。

Template.childResetPassword.helpers({
    childFirstName: function() {
        return this.profile.firstname;
    }
});

所以,@Joos答案没有错,但是经过更多的试验和错误,我找到了我正在从事的流星项目的解决方案。

我的项目(直到我环顾四周才知道)autopublish删除了流星包。因此,为了访问我的馆藏中的数据,我必须订阅它们。因此,我放置此订阅行的最佳位置是在此模板的Router.route声明中:

Router.route('/reset-password/child/:_id', {
    name: 'reset-child-password',
    template: 'childResetPassword',
    layoutTemplate: 'appLayout',
    waitOn: function() { // this is new new line/option i added to my route
        return Meteor.subscribe('users');
    },
    data: function() {
        if (this.ready()) {
            var childUser = Users.findOne({_id: this.params._id});
            if (childUser)
                return childUser;
            else
                console.error("Child User not found", childUser);
        }
        else {
            this.render("Loading");
        }
    }
});

因此,话虽如此,如果您的项目中仍有自动发布包并且打算保留它,那么您需要做的@Joos答案就是所有答案。

但是,如果您确实打算删除它,则需要上面的路由器解决方案,并确保您已在服务器上的某个位置发布了这样的用户集合:

server/publications.js

Meteor.publish("users", function () {
    return Meteor.users.find();
});