【问题标题】:Hide elements with handlebars depending on user role根据用户角色隐藏带有把手的元素
【发布时间】:2017-09-01 04:52:25
【问题描述】:

我的项目中目前有两个可能的用户,他们是雇主和候选人。

var User = new Schema({
    role:String
});

我的车把页面上有某些元素,我想根据登录的用户隐藏这些元素。这些元素只是字体很棒的图标和按钮。有没有办法通过助手或其他方式做到这一点?或者可能是 jQuery,我不确定,我使用 Passport.js 作为我的登录系统。

【问题讨论】:

    标签: jquery node.js handlebars.js passport.js roles


    【解决方案1】:
       {{#ifeq user.role 'admin'}} this will show only if user is admin {{/ifeq}}
    

    请记住,这仅在角色为字符串类型时才有效。

    【讨论】:

    【解决方案2】:

    猜你渲染页面并注入“用户”变量,这很容易做到。

    如果语句为真,则可以使用 if 语句渲染代码块

    I found this link that explains it really well.


    第一个选项

    Here's a complete answer that should help you do what you want to do. (这就是它所说的:)。

    最简单的方法是添加一个自定义 if_eq 助手:

    Handlebars.registerHelper('if_eq', function(a, b, opts) {
        if(a == b) // Or === depending on your needs
            return opts.fn(this);
        else
            return opts.inverse(this); }); and then adjust your template:
    
    {{#if_eq this "some message"}}
        ... {{else}}
        ... {{/if_eq}} 
    

    演示:http://jsfiddle.net/ambiguous/d4adQ/

    如果您的错误条目不是简单的字符串,那么您可以添加“是 这一些消息”标记给他们并使用标准的 {{#if}} (请注意 将属性直接添加到字符串不会很好):

    for(var i = 0; i

    {{#if is_status}}
        <li>Status</li> {{else}}
        <li>{{msg}}</li> {{/if}}
    

    演示:http://jsfiddle.net/ambiguous/9sFm7/


    第二个选项

    使用 Elving 的 Swag Handlebars helpers library,您可以使用助手 isisnt点击文档链接

    两个例子

    如果条件为真,则有条件地渲染一个块。

    参数:

    value [string|int] - the value to test against.
    

    用法:

    number = 5
    
    {{#is number 5}}
        Kiss my shiny metal ass!
    {{else}}
        Never mind :(
    {{/is}}
    
    => Kiss my shiny metal ass!
    

    不是

    如果条件为假,则有条件地渲染一个块。的反面 是。

    参数:

    value [string|int] - the value to test against.
    

    用法:

    number = 5
    
    {{#isnt number 5}}
        Kiss my shiny metal ass!
    {{else}}
        Never mind :(
    {{/isnt}}
    
    => Never mind :(
    

    【讨论】:

    • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接答案可能会失效。 - From Review
    • @Raidri 感谢您告诉我,我会立即编辑我的帖子。
    • 为第二个选项复制文本而不是插入图像会更好,但总体来说很好。
    • @Raidri 确实,我现在要改变它。
    猜你喜欢
    • 2021-12-01
    • 1970-01-01
    • 2018-08-09
    • 2021-08-31
    • 2021-08-05
    • 2018-07-19
    • 2012-09-16
    • 2021-09-14
    • 2019-05-17
    相关资源
    最近更新 更多