I'm not able to determine whether a variable is empty when used in the template.
I've iterated through the whole collection and in each I'm looking for a variable narrative_text
.
I tested the empty variable by
{% ifnotequal narratives.narrative_text '' %}
I notice the control enters this block, but prints nothing/blank when the
{{ narratives.narrative_text }}
is encountered.
So, how do I precisely check if the variable is empty?
I read the docs and found out that invalid/empty template variables are replaced by ''
.
The doc says that
the template system inserts the value of the
TEMPLATE_STRING_IF_INVALID
setting.
Do we have to explicitly enter that into the settings.py
? I tried doing so but still I haven't been able to make it work.
c=Context({
"narratives_list":all_narratives,
"patient_name":care_seeker_name
})
all_narratives
is returned by a pymongo database call.
{% for narratives in narratives_list %}
<tr>
<td class = "date_col">
7 Aug, 2012
</td>
{% ifnotequal narratives.narrative_text '' %}
<td>
<div class = "narrative">
( text narrative )
<b>
{{ narratives.about }}
</b>
<br><br>
{{ narratives.narrative_text }}
</div>
</td>
{% else %}
<td>
<div class="scans">
<div class="gallery">
<b> {{ narratives.about }}</b>
<br><br>
<a href="https://udhc1-nodejstest.rhcloud.com/my_image/{{ narratives.file_id }}">
<img src="https://udhc1-nodejstest.rhcloud.com/my_image/{{ narratives.file_id }}" width="72" height="72" alt="" />
</a>
</div>
</div>
</td>
{% endifnotequal %}
You can Use bool() to check if a variable is empty in Python. Or you can also use if not statement to check it.
first_name is None %} causes syntax error in Django template. Your hint mixes presentation and logic by putting HTML in your model, doing exactly the opposite of what you are trying to teach.
Django TemplateDoesNotExist error means simply that the framework can't find the template file. To use the template-loading API, you'll need to tell the framework where you store your templates. The place to do this is in your settings file ( settings.py ) by TEMPLATE_DIRS setting.
{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.
Pipe through length and do your test against that value.
{% if narratives.narrative_text|length > 0 %}
{{ narratives.narrative_text }}
{% else %}
None
{% endif %}
Just confirmed via my own code using django 2.1.3 and python 3.5 and 3.7 that the following works:
{% if narratives.narrative_text %}
# do something
{{ narratives.narrative_text }}
{% else %}
# do something else
None # displays "None"
{% endif %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With