Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to auto check checkboxes using Twig template?

Tags:

php

twig

I want to auto-check check boxes in the HTML. I've managed to get this to work, but it's kinda messy 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'm loading in is like this (in JSON format):

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

Also, I'm not using Symfony (I'm using Slim's Twig library) so not sure if Symfony has some stuff in it's framework for doing stuff with Twig. If so, it won't work for me :(

like image 722
Martyn Avatar asked Oct 30 '22 10:10

Martyn


1 Answers

The problem is the article is an array, so or you need to cycle on it for every tags array that contain or you simply access on it of the first element as follow:

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

Instead of:

    {% for article_tag in article.tags %}

See the result on this working twigfiddle

Hope this help

like image 85
Matteo Avatar answered Nov 15 '22 06:11

Matteo