How to print twig variables inside html code

2019-02-15 21:09发布

问题:

I created a variable, like this :

{% set checkboxHTML = '<button class="btn btn-default btn-md" data-id="{{b.id}}">Edit</button>' %}

Now I trying print in two ways:

  1. {{ checkboxHTML }}

Above it printed like text (no html)

  1. {{ checkboxHTML | raw }}

Print the html, but the variable {{ b.id }} doesn't take it like twig sintax, take it like text

How to print that variable inside a text ?

回答1:

Alternative method to solve this is using the expanded {% set %}
Do note when using this method, the content is considered being safe

{% set checkboxHTML %}
    <button class="btn btn-default btn-md" data-id="{{ b.id }}">Edit</button>
{% endset %}

twigfiddle



回答2:

You have to use set, like this:

{% set checkboxHTML = '<button class="btn btn-default btn-md" data-id="' ~ b.id ~ '">Edit</button>' %}

Documentation: https://twig.symfony.com/doc/2.x/tags/set.html