简体   繁体   English

Handlebars.js条件语句{{#if expression}}…{{else}}…{{/ iif}}错误

[英]Handlebars.js Conditional Statement {{#if expression}} … {{else}} … {{/iif}} Error

I am trying to implement Handlebars templating logic to show a "logged in" navbar (with a user's first name and profile image) if the user is authenticated or a "logged out" navbar if the user is not authenticated. 我正在尝试实现Handlebars模板逻辑,以在用户通过身份验证时显示“已登录”导航栏(带有用户的名字和个人资料图像),或者在用户未通过身份验证时显示“已注销”导航栏。

To do this, I am using the handlebars.js conditional statement: 为此,我使用handlebars.js条件语句:

{{#if login_status}}
     *logged in navbar html code*
{{else}}
     *logged out navbar html code*
{{/if}}

I am also using a helper login_status.js that returns true if authenticated and false is not authenticated, based on the existence of a user's ID. 我还使用了一个帮助程序login_status.js ,如果用户通过了身份验证,则返回true;如果未通过身份验证,则返回false My helper code looks like this: 我的助手代码如下所示:

module.exports = function(l) {
    if (l.data.root.id === undefined) {
        console.log('user is logged out');
        return false;
    } else {
        console.log('user is logged in: ', l.data.root.id);
        return true;
    }
};

However, this does not work, and it is always returning the {{else}} statement, meaning that the user is not authenticated. 但是,这是行不通的,它总是返回{{else}}语句,这意味着用户未通过身份验证。

Is there a better way of implementing this logic? 有没有更好的方法来实现这种逻辑? Is the helper code incorrect? 辅助代码不正确吗? Is the handlebars {{#if}} expression incorrect? 车把{{#if}}表达式是否正确?

Any help is appreciated. 任何帮助表示赞赏。

Thanks! 谢谢!

Jesse 杰西

phkavitha trying to say is that you can use (login_status function) as a property(getter) instead of a helper. phkavitha试图说的是,您可以使用(login_status函数)作为属性(getter)来代替助手。

you can say: 你可以说:

var template = Handlebars.compile([your handlebars template]);
var html = template({
     ...
     get login_status() {
        return require('login_status.js')(l);
     }, 
     ...
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM