Now that we've covered the template-loading mechanism, we can introduce a built-in template tag that takes advantage of it: {% include %}
. This tag allows you to include the contents of another template. The argument to the tag should be the name of the template to include, and the template name can be either a variable or a hard-coded (quoted) string, in either single or double quotes.
Anytime you have the same code in multiple templates, consider using an {% include %}
to remove the duplication. These two examples include the contents of the template nav.html
. The examples are equivalent and illustrate that either single or double quotes are allowed:
{% include 'nav.html' %} {% include "nav.html" %}
This example includes the contents of the template includes/nav.html
:
{% include 'includes/nav.html' %}
This example includes the contents of the template whose name is contained in the variable template_name
:
{% include template_name %}
As in get_template...