Home > database >  How to replace a string in template twig?
How to replace a string in template twig?

Time:12-02

I have a template twig in html for example:

<p>Test document</p>

<p>However</p>

I would like to replace the word 'Test' in the include template. {% include '@template/testing' %}

Is there some solution to replace the word in the include statement?

I tried to use replace inside the {% include '@template/testing' %} but I don`t how to start it.

CodePudding user response:

Take a closer look at the docs:

Included templates have access to the variables of the active context.
...
You can add additional variables by passing them after the with keyword:

{# 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 %}

You can disable access to the context by appending the only keyword:

{# 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

That means you can set a variable in the current template and reference the variable in the included template, where you can also define a default value.

template/testing:

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

<p>However</p>

current template:

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

Or pass it directly in one line:

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

Same, but included template will not have access to the variables of the active context:

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

Any of these methods will render:

<p>new name document</p>

<p>However</p>

Here is a good explanation for all this.

CodePudding user response:

I found a solution

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

{% if 'Hi' in block_modify %}

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

{% endif %}
  • Related