在每个语句中嵌套 If

Nested If in Each Statement

我有一个应用程序,允许组内的用户查看每个成员发给组的消息,并在我的视图中使用 {{#each comment}} 列出它们。我想将任何评论的编辑限制为仅与使用 {{#if user.user_id}} 的登录用户关联的那些评论。

我试图在我的每个部分中嵌套一个 if 语句,但它没有隐藏那些不符合这种情况的编辑 link。这是因为没有 else 语句吗?难道嵌套的if来自不同的对象?

这是我的看法:

{{#each comment}}
    <div class="col-md-7 col-md-offset-5 comment-card">
        <div class="comment-card-header">
            <p class="card-date">{{this.commentDateSlug}}</p>
            <h3 class="card-title">{{this.title}}</h3>
        </div>
        <div class="comment-card-body">
            <p class="card-report-link">Report: <a href="{{this.commentLink}}" class="card-data-report-url">{{comment.reportLink}}</a></p>
        </div>

        {{#if user.user_id}}
        <p>This is the user: {{user.user_id}}</p>
        <div class="annotation-card-footer">
            <a href="/app/edit/{{this.commentId}}">Edit</a>
        </div>
        {{/if}}
    </div>
{{/each}}

路线如下:

appRoutes.route('/') 

    .get(function(req, res){

        models.Comment.findAll({
            attributes: ['commentId', 'commentDate', 'dataDateStart', 'dataDateEnd', 'title', 'discovery', 'reportLink'],
            order: 'commentDate DESC',
            include: [{
                model: models.User,
                where: { organizationId: req.user.organizationId },
                attributes: ['organizationId', 'user_id']
            }]
        }).then(function(comment){
            res.render('pages/app/high-level-activity-feed.hbs',{
                comment: comment,
                user: req.user
            });
        })
    })

听起来您想在模板中做的是只为 user_id 等于当前用户的 评论呈现 div.annotation-card-footer user_id.

在伪代码中,这将类似于以下内容:

if current_user.user_id equals comment.user_id:
    render div

Handlebars 不支持比较运算符,因此我们需要自己编写 block helper. There are existing resources about how to do this, see this link,但我会提供一个示例:

Handlebars.registerHelper('ifeq', function (value1, value2, options) {
    return ((value1 === value2) ? options.fn(this) : options.inverse(this));
});

现在我们已经注册了我们的助手,我们可以在我们的模板中使用它了:

{{#ifeq this.user_id ../user.user_id}}
    <p>This is the user: {{../user.user_id}}</p>
    <div class="annotation-card-footer">
        <a href="/app/edit/{{this.commentId}}">Edit</a>
    </div>
{{/ifeq}}

使用 block helper 的一个优点是我们可以很容易地添加一个 else 分支:

{{#ifeq this.user_id ../user.user_id}}
    <p>This is the user: {{../user.user_id}}</p>
    <div class="annotation-card-footer">
        <a href="/app/edit/{{this.commentId}}">Edit</a>
    </div>
{{else}}
    {{! Non-current-user stuff goes here. }}
{{/ifeq}}