Home > Software engineering >  Replace Filter - How to pass a variable for the string to be replaced?
Replace Filter - How to pass a variable for the string to be replaced?

Time:08-26

I am currently working on a symfony 6 project and try to pass a variable into a replace filter from Twig. However that does not work for me.

I tried it like this:

    {% if form.vars.data.fileName|default %}
        {% set system_type_short = get_env("SYSTEM_TYPE_SHORT") %}
        {% set replaces = '/var/www/' ~ system_type_short ~ '.domain.de/public/uploads/images/' %}
        {% set url = 'uploads/images/' ~ form.vars.data.fileName|replace({(replaces): ('')}) %}
        <img src="{{ asset(url) }}" height="100"><br><br>
    {% endif %}

The error I get: A hash key must be followed by a colon (:). Unexpected token "punctuation" of value "{" ("punctuation" expected with value ":").

Can anyone tell me what I am doing wrong or how to pass a variable into the filter function "replace"?

CodePudding user response:

You cannot use the variable syntax ({{ }}) when already in a twig expression.

So you just have to fix {{system_type_short}} and use string concatenation ~ instead.

You would get:

{% if form.vars.data.fileName|default %}
    {% set system_type_short = get_env("SYSTEM_TYPE_SHORT") %}
    {% set url = 'uploads/images/' ~ form.vars.data.fileName|replace({('/var/www/' ~ system_type_short ~ '.domain.de/public/uploads/images/'): ''}) %}
    <img src="{{ asset(url) }}" height="100"><br><br>
{% endif %}
  • Related