Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply conditional attribute to HTML element in template?

I have a checkbox in my Django jinja template. I want that checkbox to be checked if object boolean field is True.

My html element looks like:

<div class="checkbox"><label>
<input type="checkbox" name="sendEmail" checked="{{ customer.SendSms }}">
Send sms?
</label></div>

The problem is, checkbox is still checked when attribute checked="False", it's becomes unchecked only when the checked attribute is not there.

So what i need is, put checked attribute into the html element only if customer.SendSms is true.

I know something like

{% if customer.SendSms %}
//checked html element here
{% else %}
//unchecked element here
{% endif %}

possible but this does not look so pretty, is there any other good way to handle this?

like image 549
Sefa Avatar asked Feb 21 '15 10:02

Sefa


2 Answers

Why not wrap the attribute in a conditional?

<input type="checkbox" name="sendEmail" {% if customer.SendSms %}checked{% endif %}>
like image 62
rnevius Avatar answered Nov 12 '22 14:11

rnevius


yesno template filter will do the job:

<input type="checkbox" name="sendSms" {{ customer.SendSms|yesno:"checked" }}>
like image 41
catavaran Avatar answered Nov 12 '22 16:11

catavaran