簡體   English   中英

如何替換模板 twig 中的字符串?

[英]How to replace a string in template twig?

例如,我在 html 中有一個模板 twig:

<p>Test document</p>

<p>However</p>

我想替換包含模板中的“測試”一詞。 {% include '@template/testing' %}

是否有一些解決方案可以替換 include 語句中的單詞?

我嘗試在{% include '@template/testing' %}中使用替換,但我不知道如何啟動它。

仔細看看文檔:

包含的模板可以訪問活動上下文的變量。
...
您可以通過在 with 關鍵字之后傳遞它們來添加其他變量:

 {# template.html will have access to the variables from the current context and the additional ones provided #} {% include 'template.html' with {'foo': 'bar'} %} {% set vars = {'foo': 'bar'} %} {% include 'template.html' with vars %}

您可以通過附加 only 關鍵字來禁用對上下文的訪問:

 {# only the foo variable will be accessible #} {% include 'template.html' with {'foo': 'bar'} only %} {# no variables will be accessible #} {% include 'template.html' only %}

-- https://twig.symfony.com/doc/2.x/tags/include.html

這意味着您可以在當前模板中設置一個變量並在包含的模板中引用該變量,您還可以在其中定義一個默認值。

模板/測試:

<p>{{ doc_name|default('Test') }} document</p>

<p>However</p>

當前模板:

{% set doc_name = 'new name' %}
{% include '@template/testing' %}

或者直接在一行中傳遞它:

{% include '@template/testing' with {'doc_name':'new name'} %}

相同,但包含的模板將無法訪問活動上下文的變量:

{% include '@template/testing' with {'doc_name':'new name'} only %}

這些方法中的任何一個都將呈現:

<p>new name document</p>

<p>However</p>

這是對這一切的一個很好的解釋。

我找到了解決方案

{%- set block_modify -%}
{% include 'template.html' %}
{%- endset -%}

{% if 'Hi' in block_modify %}

{{ block_modify | replace ({'Hi':'Hello'}) | raw}}

{% endif %}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM