Search code examples
pythonhtmljinja2

Flask - how to dynamically set 'checked' property to an input checkbox


How can I dynamically add checked property to my input checkbox, assuming my object has an active property?

{% for object in objects %}
    <li>
        <input type="checkbox" id="id_{{object.id}}" name="checkbox" value={{object.id}}>
    </li>
{% endfor %}

Adding checked="{{object.active}}" did not work.


Solution

  • To add the checked property to your checkbox input element, you can dynamically add it like this:

    <input type="checkbox" id="id_{{object.id}}" name="checkbox" value={{object.id}} {{'checked' if object.active else ''}}>