For example, if we need display a table of items on a given page, rather than putting all the code we can write the code for the table in a different template page, and include it on the 'main' one, like this:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{% include "table_frag.html" %} |
Once you start using include, you'd start thinking on how to pass values to the included templates so they behave somewhat different each way, much like you pass parameters to functions; you can just modify variables in the main template before including, since the sub-template has access to all those variables; however, django provides a nicer syntax.
You can use with, and specify a value for a new variable, that will exist only in the included template. For example:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{% with 'Orlando' as name%} | |
{% include 'salutation.html'%} | |
{% endwith %} |
As a real-life example, I am developing a program to deal with applications to our department; each application passes through different stages, and we need to display applications on each of those stages on each page, so I'm doing something like:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{% if unreviewed_apps.count %} | |
<h2>Unreviewed Applications</h2> | |
{% with unreviewed_apps as apps%} | |
{% include "application_table_frag.html" %} | |
{% endwith %} | |
{% endif %} | |
{% if reviewed_apps.count %} | |
<h2>Reviewed Applications</h2> | |
{% with reviewed_apps as apps%} | |
{% include "application_table_frag.html" %} | |
{% endwith %} | |
{% endif %} |
No comments:
Post a Comment