How to check checkboxes using Twig template?

I want to check the boxes for automatic validation in HTML. I managed to get this to work, but it is a bit dirty in the template:

<ul>
    {% for tag in tags %}
        {% set selected = false %}
        {% for article_tag in article.tags %}
            {% if article_tag.id == tag.id %}
                {% set selected = true %}
            {% endif %}
        {% endfor %}
        <li><input type="checkbox" name="tags[]" value="{{ tag.id }}" {% if selected %}checked{% endif %}> {{ tag.name }}</li>
    {% endfor %}
</ul>

So, the data I upload looks like this (in JSON format):

[
    'tags' => [
        {'id'=> 1, 'name'=>'Travel'},
        {'id'=> 2, 'name'=>'Cooking'},
    ],
    'article' => {
        'tags' => [
            {'id'=> 1, 'name'=>'Travel'},
        ],
    }
]

Also, I don’t use Symfony (I use the Slim Twig library), so I’m not sure that Symfony has something in this Twig framework. If so, this will not work for me :(

+4
source share
1 answer

The problem is that the article is an array, so you need to cycle through it for each tag array that contains or you simply access the first element as follows:

    {% for article_tag in article[0].tags %}

Instead:

    {% for article_tag in article.tags %}

twigfiddle

+1

Source: https://habr.com/ru/post/1625712/


All Articles