[英]Meteor, how to access to a helper from another helper?
I have a helper like 我有一个好帮手
Template.user_profile.helpers({
user:function() {
return Meteor.users.find({'profile.front_name':Session.get('slug')}).fetch()[0];
}
});
I want to add a helper to the collection which could access the user
helper and compare its _id
with the current user _id
, to tell whether the user is visiting its own profile. 我想在集合中添加一个帮助程序,它可以访问user
帮助程序并将其_id
与当前用户_id
进行比较,以判断用户是否正在访问自己的配置文件。 I'm using something pretty ugly: 我正在使用一些非常难看的东西:
Template.user_profile._tmpl_data.helpers.user()
The final code: 最终代码:
Template.user_profile.helpers({
user:function() {
return Meteor.users.find({'profile.front_name':Session.get('userId')}).fetch()[0];
},
isCurrentUser: function() {
return Template.user_profile._tmpl_data.helpers.user()._id === Meteor.userId();
}
});
Is there any better way to access another helper? 有没有更好的方法来访问另一个帮手?
I've just accidentally discovered this in the console: 我刚刚在控制台中意外地发现了这个:
Template.registerHelper
function (name, func) {
Blaze._globalHelpers[name] = func;
}
So, Blaze._globalHelpers
is what we are looking for! 所以, Blaze._globalHelpers
是我们正在寻找的!
You can call a template helper (not global helper - which is in outluch's answer) with: 您可以使用以下命令调用模板帮助程序(不是全局帮助程序 - 这是outluch的答案)
Template.tplName.__helpers.get('helper').call()
MDG suggests using a regular function and then passing it to helpers, events and so on. MDG建议使用常规函数,然后将其传递给帮助程序,事件等。 See here . 看到这里 。
Update 16.06.16 更新16.06.16
Actually I strongly advise to simply use manuel:viewmodel - it alleviates so many Blaze headaches... 实际上我强烈建议简单地使用manuel:viewmodel - 它减轻了很多Blaze的头痛......
As I was searching for a way to call a helper from another helper, I found that Meteor 1.0 defines "Template.registeredHelpers" that are available for all other helpers to use. 当我在寻找一种从另一个助手调用帮助器的方法时,我发现Meteor 1.0定义了“Template.registeredHelpers”,可供所有其他助手使用。 https://docs.meteor.com/#/full/template_registerhelper https://docs.meteor.com/#/full/template_registerhelper
Template.registerHelper("checkedIf",function(value){
return value?"checked":"";
});
You might not even need to call a helper like that. 您可能甚至不需要像这样调用帮助器。 There is a currentUser helper already built in. 已经内置了currentUser助手。
http://docs.meteor.com/#template_currentuser http://docs.meteor.com/#template_currentuser
{{currentUser}}
maybe this would work for you: 也许这对你有用:
//js
Template.foo.helpers({ bar: function() {
return this.userId == Meteor.userId(); },
domain: function() {
var a = document.createElement('a'); a.href = this.url;
return a.hostname;
} });
ownsDocument = function(userId, doc) { return doc && doc.userId === userId;}
Posts = new Meteor.Collection('posts');
Posts.allow({
update: ownsDocument, remove: ownsDocument
});
//html
{{#if bar}}<a href="{{pathFor 'postEdit'}}">Edit</a>{{/if}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.