Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TWIG REPLACE not Working

Tags:

twig

I have the following twig code:

{% set button_class = button_class_off|default('toggle toggle-thumbs-down') %}

{% set button_toggle_swap = button_toggle_swap|default(['toggle-thumbs-down', 'toggle-thumbs-up']) %}

{% if value == '1' %}
    {% dump(name) %}

    {% for swap in button_toggle_swap %}
        {% if swap in button_class %}
            {% dump(swap) %}
            {% dump(button_class) %}
            {% set button_class = button_class|replace({swap: ""})|trim %}
            {% dump(button_class) %}
        {% else %}
            {% set button_class = button_class ~ ' ' ~ swap %}
        {% endif %}
    {% endfor %}
{% endif %}

The dump shows:

"hifi"

"toggle-thumbs-down"

"toggle toggle-thumbs-down"

"toggle toggle-thumbs-down"

I have no idea why the replace does not work. I have tried this with and without the trim. The result is that the replace of swap with "" is ignored.

Any idea what I am doing wrong here?

like image 513
Craig Rayner Avatar asked Dec 06 '25 13:12

Craig Rayner


1 Answers

OK. There appears to be some missing details in the documentation. If using a variable (not an absolute string) the the variable must be wrapped in parenthesis ().

This code works:

{% set button_class = button_class_off|default('toggle toggle-thumbs-down') %}

{% set button_toggle_swap = button_toggle_swap|default(['toggle-thumbs-down', 'toggle-thumbs-up']) %}

{% if value == '1' %}
    {% for swap in button_toggle_swap %}
        {% if swap in button_class %}
            {% set button_class = button_class|replace({(swap): ""})|trim %}
        {% else %}
            {% set button_class = button_class ~ ' ' ~ swap %}
        {% endif %}
    {% endfor %}
{% endif %}

Thanks to this answer to str_replace in twig

like image 120
Craig Rayner Avatar answered Dec 11 '25 22:12

Craig Rayner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!