簡體   English   中英

如何在Handlebars.js的循環中比較兩個屬性,其中一個屬性在循環范圍之外?

[英]How can I compare two attributes in a loop in Handlebars.js where one attribute is outside the loop scope?

我正在使用Handlebars.js根據字符串是否與當前用戶的用戶名匹配來顯示元素。

我實際上是遍歷一個收藏blogs而這正是屬性author發揮作用的地方。 無論如何, author.username代表一些用戶名字符串,我可以使用它。 我的問題是,如果我將user.attributes.username更改為一些預定義的字符串,即“ martin”,則條件將檢出,並以所需的方式顯示該元素。 但是我還有一個屬性user.attributes.username ,它在#ifEquals條件之外也可以user.attributes.username顯示。 我真的想將author.username與此屬性進行比較,而不是將一些預定義的字符串進行比較。

如何比較兩個屬性,即author.usernameuser.attributes.username而不是author.username"martin"

author.usernameuser.attributes.username都具有相同的值。 目前這對我不起作用,但我最終想要的是:

{{#each blog}}
        {{#ifEquals author.username user.attributes.username}}
            <a href="#" onClick="return false;"><span class="delete-container" style="cursor: pointer" data-blog-id="{{objectId}}"><span class="typcn typcn-arrow-sorted-down hvr-pulse-grow" style="color: gray; font-size: 30px;"></span></span></a>
        {{/ifEquals}}
{{/each}}

這有效,但不足以達到我的目的:

{{#each blog}}
        {{#ifEquals author.username "martin"}}
            <a href="#" onClick="return false;"><span class="delete-container" style="cursor: pointer" data-blog-id="{{objectId}}"><span class="typcn typcn-arrow-sorted-down hvr-pulse-grow" style="color: gray; font-size: 30px;"></span></span></a>
        {{/ifEquals}}
{{/each}}

Handlebars.js幫助器:

<script>
    Handlebars.registerHelper('ifEquals', function(arg1, arg2, options) {
        return (arg1 == arg2) ? options.fn(this) : options.inverse(this);
    });
</script>

編輯:經過進一步檢查,看來問題在於user.attributes.username不會在blog循環中呈現。 它認為userblog一個屬性。 有沒有什么辦法可以訪問user ,就好像它不在循環范圍之內?

顯然,您可以通過添加../來訪問Handlebars.js中的外循環屬性。

{{currentUser.username}} // Renders fine outside the loop

 {{#each blog}}
    // Append ../ to access currentUser inside the loop
    {{#ifEquals author.username ../currentUser.username}}
        // Show element here
    {{/ifEquals}}
 {{/each}}

../user是來自blog循環外部的屬性,而author屬於blog

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM