![](/img/trans.png)
[英]Access a variable outside the scope of a Handlebars.js each loop
[英]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.username
和user.attributes.username
而不是author.username
和"martin"
?
author.username
和user.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
循環中呈現。 它認為user
是blog
一個屬性。 有沒有什么辦法可以訪問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.