-1

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"?

schwaluck
  • 115
  • 9

1 Answers1

2

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 %}
Dylan KAS
  • 4,840
  • 2
  • 15
  • 33
  • 1
    This will not work. If you use variables in the key you need to wrap the key in parentheses. See [here](https://stackoverflow.com/questions/43794257/how-to-use-variables-in-twig-filter-replace) - [demo](https://twigfiddle.com/zpkuat) – DarkBee Aug 25 '22 at 13:57
  • Thank you I forgot about this, I edited it. – Dylan KAS Aug 25 '22 at 14:23
  • Thank you both. I have adjusted my code accordingly and now it works. The correct code is now in my post. – schwaluck Aug 25 '22 at 15:40