Inlines Python/Django technique for objects
I am reading the source code of the Django application blog at git://github.com/nathanborror/django-basic-apps.git
.
How do you r开发者_如何学运维ead the following Django code?
{% tags_for_object object as tag_list %}
My attempt: Make the variable object of the type tags_for_object and rename the variable to tag_list.
The object apparently is based on the file blog/templates/inlines/default.html:
{% if object %}
{{ object }}
{% else %}
{% for object in object_list %}
{{ object }}
{% endfor %}
{% endif %}
What is the befefit of putting the logic to two-step procedure: run single object, else loop through a list of objects?
It looks like tags_for_object
is the template tag from the django-tagging application.
From the django-tagging documentation:
tags_for_object:
Retrieves a list of
Tag
objects associated with an object and stores them in a context variable.Usage:
{% tags_for_object [object] as [varname] %}
Example:
{% tags_for_object foo_object as tag_list %}
You can then loop through the tag_list
variable in the template to display the tags.
{% tags_for_object foo_object as tag_list %}
<ul>
{% for tag in tag_list %}
<li>{{ tag }}</li>
{% endfor %}
</ul>
For the second part of your question, you understand the code correctly. If the variable object
exists in the context (and doesn't evaluate to False), it is displayed. If it does not exist in the context (or if it evaluates to False), then the code loops through the objects
in object_list
, and displays them.
As for why you would want to do this, you would have to look at the code that uses inlines/default.html
to work out what the designer had in mind.
精彩评论