You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nunjucks宏中如何让set语句解析collection_name的实际集合值?

Nunjucks中动态访问集合的解决方法

你现在的问题出在:拼接得到的collection_name只是字符串形式的路径(比如"collections.pages"),Nunjucks不会自动把这个字符串解析成实际的集合对象,所以过滤器自然无法正确处理。

不用拼接字符串,直接利用对象的括号访问语法就能解决:因为collections是一个对象,rel_content_sections_post_type的值就是你要访问的集合名称(比如pages),直接通过collections[rel_content_sections_post_type]就能拿到对应的集合对象。

修改后的代码如下:

{# 直接通过括号语法获取目标集合,无需拼接字符串 #}
{% set target_collection = collections[rel_content_sections_post_type] %}

<p>当前使用的集合是 collections.{{ rel_content_sections_post_type }}</p>

{% set related_item = target_collection | findInCollectionByPropertyAndValue('data.slug', item) %}

这种写法是Nunjucks中动态访问对象属性的标准方式,能直接拿到你需要的集合实例,而非路径字符串。

内容的提问来源于stack exchange,提问作者James

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 20:24:52