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
相关产品推荐
相关产品推荐

