在Twig v1.x与Timber v1.x中if语句内嵌cache标签报错求方案
解决Twig 1.x/Timber 1.x中条件缓存标签报错的问题
问题原因
Twig的模板解析器严格遵循标签嵌套规则,你将{% cache %}和{% endcache %}分别放在两个独立的{% if %}块中,解析器无法识别它们是一对匹配的标签,因此抛出"Unexpected 'endif' tag (expecting closing tag for the 'cache' tag)"错误。
解决办法
方法1:将缓存块整体包裹在条件判断内
把需要缓存的代码和完整的cache标签都放在is_prod的条件块中,非生产环境直接执行代码,避免标签拆分:
{% if is_prod %} {% cache 'homepage;' ~ hash_key ~ ';' post %} <!-- 这里是你的业务代码 --> ...code {% endcache %} {% else %} <!-- 非生产环境直接执行相同代码 --> ...code {% endif %}
方法2:使用宏避免代码重复
如果业务代码较长,为了避免重复编写,可以用Twig宏封装重复代码:
{# 定义宏封装业务代码 #} {% macro render_homepage_content() %} ...code <!-- 这里是你的业务代码 --> {% endmacro %} {# 条件控制缓存逻辑 #} {% if is_prod %} {% cache 'homepage;' ~ hash_key ~ ';' post %} {{ _self.render_homepage_content() }} {% endcache %} {% else %} {{ _self.render_homepage_content() }} {% endif %}
方法3:使用Timber缓存函数(替代标签)
Timber 1.x支持使用cache()和endcache()函数来替代标签语法,这种方式允许将缓存的开始和结束放在不同的条件块中:
{% if is_prod %} {{ cache('homepage;' ~ hash_key ~ ';', post) }} {% endif %} ...code <!-- 你的业务代码 --> {% if is_prod %} {{ endcache() }} {% endif %}
内容的提问来源于stack exchange,提问作者Luka Juras
相关产品推荐
相关产品推荐

