Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django template display item value or empty string

My code in template is like this:

{% for item in items %}
    {{ item.somefield }}
{% endfor %}

I want to display the item value if the item.somefield is not None, or display an empty string. I don't want to use the {% if item.somefield %} statement, I want something like {{ item.somefield or '' }}(I tried this but it doesn't work)

like image 974
Roger Liu Avatar asked May 09 '13 10:05

Roger Liu


2 Answers

You want the default_if_none template filter, (doc).

default_if_none will display the given string if the variable is 'None'.

default will display the string if the variable evaluates to False, ie empty strings, empty lists etc

{{ item.somefield|default_if_none:"" }}
{{ item.somefield|default:"" }}
like image 134
rockingskier Avatar answered Oct 02 '22 14:10

rockingskier


{{ item.somefield|default_if_none:"" }}
like image 41
matino Avatar answered Oct 02 '22 14:10

matino