0

There is a variable preparing in PHP for rendering in a Twig template like

{{ product.variations.0.add_to_cart_form }}

And I need to change the final rendered result by adding my additional string to it.

The problem is, the value of the key add_to_cart_form is not a string. It's maybe a result of executing some PHP function or is an element of an array. I don't understand how exactly it's prepared in PHP, but I need to change the final result simply by applying the filter |replace({'some_string':'some_string and_more'}). If it's possible.

If I put the line {{ product.variations.0.add_to_cart_form }} to a new template, include it in the parent template and add to a new variable like

{% set test %}
    {% include directory ~ '/templates/addtocartform.html.twig' %}
{% endset %}
{% set test = test.replace({'some_string':'some_string and_more'}) %}
{{ test }}

I get nothing on the page. Again, as I understand because the variable is not a string.

Is there a way to "convert" it to a string and then apply the filter |replace() regardless of the type of the variable ?

Something like template_to_string (do not be confused with template_from_string)

stckvrw
  • 1,689
  • 18
  • 42
  • 1
    `test.replace` is not a valid syntax this would `test` to be an object or an array. Did you actually try to do [`{{ test|replace(...) }}`](https://twigfiddle.com/d0dmdy)? – DarkBee Mar 06 '23 at 12:50
  • @DarkBee Sorry, it was a typo. Now if I try `|replace()` I get ``. I see it's Drupal-specific issue – stckvrw Mar 06 '23 at 13:06
  • 1
    The filter replace doesn't mark a string as safe. If you want output "real" HTML you would need to apply the filter `raw` as well. See [here](https://stackoverflow.com/questions/8355123/how-to-display-string-that-contains-html-in-twig-template) – DarkBee Mar 06 '23 at 13:09
  • @DarkBee Yes, the `{{ test|raw }}` renders the real HTML instead of ` – stckvrw Mar 06 '23 at 13:23
  • No, you'd apply the filter raw *after* you've used the filter `replace`, e.g. `{{ var|replace({'x':'y';})|raw }}` – DarkBee Mar 06 '23 at 13:29

0 Answers0