模板中的复杂数组搜索
Complex Array Search in Template
我正在尝试设置一种将注册者列表添加到 apostrophe-events 模块的方法。我能够向模块添加一个新的 joinByMany 字段,但我意识到我还需要存储注册日期并计算每个注册对象。为了适应这一点,我添加了以下字段,由一组 joinByOne 用户、注册日期字符串和注册计数整数组成:
addFields: [
{
name: '_registrants',
label: 'Registrants',
type: 'array',
titleField: '_user.firstName',
schema: [
{
name: '_user',
withType: 'apostrophe-user',
type: 'joinByOne',
idField: 'userId',
filters: {
// Fetch just enough information
projection: {
id: 1,
username: 1,
firstName: 1,
lastName: 1,
email: 1
}
}
},
{
name: 'registrationDate',
label: 'Registration Date',
contextual: true,
type: 'string'
},
{
name: 'attendeeCount',
label: 'Total Attendees',
type: 'integer'
}
]
}
]
现在,我 运行 遇到的问题是我想在我的 apostrophe-events-pages show.html 上显示 'Register' 或 'Unregister' 按钮模板,取决于当前登录的用户是否在 _registrants 数组中。以前,当我使用 joinByMany 设置用户列表时,我只能在 JoinByMany 的 idsField 中查找当前用户 ID 的索引。但是,现在,我必须以某种方式遍历 _registrants 并检查每个项目 _user.userId 以检查相同的内容,但我不知道该怎么做。我猜这将是模板中的某种逻辑,但我不确定如何在 nunjucks 中完成它。
这是我目前在使用 joinByMany 而不是 joinByOnes 数组时必须为用户检查的内容:
{% if data.piece.userIds.indexOf(data.user._id) < 0 %}
<div class="event-controls-item">
{{ buttons.major('Register for Field Trip', { action: 'register-event' }) }}
</div>
{% else %}
<div class="event-controls-item">
{{ buttons.danger('Unregister for Trip', { action: 'unregister-event' }) }}
</div>
{% endif %}
谢谢!
您可以使用 apos.utils.find
最轻松地做到这一点:
{% set registrant = apos.utils.find(data.piece._registrants, '_id', data.user._id) %}
{% if registrant %}
...
{% else %}
...
{% endif %}
我正在尝试设置一种将注册者列表添加到 apostrophe-events 模块的方法。我能够向模块添加一个新的 joinByMany 字段,但我意识到我还需要存储注册日期并计算每个注册对象。为了适应这一点,我添加了以下字段,由一组 joinByOne 用户、注册日期字符串和注册计数整数组成:
addFields: [
{
name: '_registrants',
label: 'Registrants',
type: 'array',
titleField: '_user.firstName',
schema: [
{
name: '_user',
withType: 'apostrophe-user',
type: 'joinByOne',
idField: 'userId',
filters: {
// Fetch just enough information
projection: {
id: 1,
username: 1,
firstName: 1,
lastName: 1,
email: 1
}
}
},
{
name: 'registrationDate',
label: 'Registration Date',
contextual: true,
type: 'string'
},
{
name: 'attendeeCount',
label: 'Total Attendees',
type: 'integer'
}
]
}
]
现在,我 运行 遇到的问题是我想在我的 apostrophe-events-pages show.html 上显示 'Register' 或 'Unregister' 按钮模板,取决于当前登录的用户是否在 _registrants 数组中。以前,当我使用 joinByMany 设置用户列表时,我只能在 JoinByMany 的 idsField 中查找当前用户 ID 的索引。但是,现在,我必须以某种方式遍历 _registrants 并检查每个项目 _user.userId 以检查相同的内容,但我不知道该怎么做。我猜这将是模板中的某种逻辑,但我不确定如何在 nunjucks 中完成它。
这是我目前在使用 joinByMany 而不是 joinByOnes 数组时必须为用户检查的内容:
{% if data.piece.userIds.indexOf(data.user._id) < 0 %}
<div class="event-controls-item">
{{ buttons.major('Register for Field Trip', { action: 'register-event' }) }}
</div>
{% else %}
<div class="event-controls-item">
{{ buttons.danger('Unregister for Trip', { action: 'unregister-event' }) }}
</div>
{% endif %}
谢谢!
您可以使用 apos.utils.find
最轻松地做到这一点:
{% set registrant = apos.utils.find(data.piece._registrants, '_id', data.user._id) %}
{% if registrant %}
...
{% else %}
...
{% endif %}