如何在Twig的include模板语句中替换指定字符串?
Twig引入模板时替换指定文本的解决方案
方法一:修改子模板传递变量(推荐)
这是最符合Twig设计思路的方案,直接让子模板支持动态文本:
- 将子模板
@template/testing的内容修改为:
<p>{{ title|default('Test') }} document</p> <p>However</p>
这里default('Test')保证不传参数时仍显示原文本。
2. 引入模板时传递替换后的文本:
{% include '@template/testing' with { title: '自定义文本' } %}
方法二:使用filter过滤器直接处理输出
如果无法修改子模板,可通过filter结合replace捕获并替换include的内容:
{% filter replace({ 'Test': '自定义文本' }) %} {% include '@template/testing' %} {% endfilter %}
注意:该方式会替换内容中所有匹配的“Test”,需确认是否符合需求。
方法三:捕获内容到变量后处理
也可以先把模板内容存入变量,再进行替换输出:
{% set template_output %} {% include '@template/testing' %} {% endset %} {{ template_output|replace({ 'Test': '自定义文本' }) }}
适合需要重复使用处理后内容的场景。
内容的提问来源于stack exchange,提问作者thomasf10
相关产品推荐
相关产品推荐

