Abid A
Abid A

Reputation: 7858

Checking against a unicoded list of strings in template

I have the following code in my template (please note the if statement):

{% for base in bases %}
    <label class="checkbox">
        <input name="base" value={{ base.id }} type="checkbox" 
           {% if base.id in selected_bases %}checked="checked" {% endif %}/>
        <span>{{ base.name }}</span>
    </label>
{% endfor %}

The selected_bases variable is a list of unicoded strings: [u'3', u'1', u'5']. base.id is an integer.

How can I make them the same type so that if statement does what I need it to?

Upvotes: 0

Views: 82

Answers (2)

Eduardo Ivanec
Eduardo Ivanec

Reputation: 11862

You should probably do this in the view instead, but you can pipe the list values through the add filter, which does type coercion - or pipe the ints to slugify, which will do the reverse. More information here.

Upvotes: 0

gruszczy
gruszczy

Reputation: 42198

I don't know if this work, but try this:

{% if value|stringformat:"d" in selected_bases %}

Upvotes: 1

Related Questions