Thursday, September 13, 2012

including templates with variables

When designing code, we usually divide it into different functions or procedures, to simplify each piece of the code. Django's template system allows us to include a sub-template (there's nothing special about sub-templates, just how you thin about them).
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:
The template you include has access to all the variables in the 'main' template.
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:
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: Since there are only a few stages, I'm directly including for each one; if there were a large number, I'd probably put them in a dictionary, and iterate through them, but this saves me effort and ensures all tables look the same.

No comments:

Post a Comment