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

Nunjucks设置链接切换逻辑时出现set语句块结束语法错误求解

解决Nunjucks状态切换链接的语法错误

你的问题出在混合使用了inline条件判断和块级endif语法,Nunjucks不支持这种写法。以下是两种正确的实现方式:

方式1:使用三元运算符(适合简单二选一逻辑)

直接在set语句里用三元表达式完成分支判断,语法更简洁:

{% set prototypeLinks = [
    data['from'] == 'contentpage' 
        ? {href: 'thispage?from=indexpage', text: 'Reset the list of options'} 
        : {href: 'thispage?from=indexpage', text: 'Reduce the options'}
] %}

方式2:使用块级条件语句(适合复杂逻辑扩展)

如果后续需要添加更多分支,用块级if/else结构更清晰:

{% set prototypeLinks = [] %}
{% if data['from'] == 'contentpage' %}
    {% set _ = prototypeLinks.push({href: 'thispage?from=indexpage', text: 'Reset the list of options'}) %}
{% else %}
    {% set _ = prototypeLinks.push({href: 'thispage?from=indexpage', text: 'Reduce the options'}) %}
{% endif %}

错误原因说明

你原来的代码试图在数组的inline if后面直接加else和endif,这不符合Nunjucks的语法规则。inline条件(不带else)可以直接写在表达式里,但带else的分支要么用三元运算符,要么拆分成块级语句处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 02:35:16