Django: inline include tag and custom include tag

What is the difference between Django's built-in include tag and custom include tags ?

I read the documentation, and both seem to have accomplished the same goal: render a template that passes a context or variable to it.

+8
django django-templates
source share
3 answers

They serve for different purposes. The include tag simply includes the entire content of the existing template and is unmodified. A custom inclusion tag passes context to a function, which may contain logic to control the context before passing it to the template.

For example, maybe I have a panel that will appear on multiple pages. A panel template requires several specific requests that must be passed to it through the context. Pages containing a panel do not require these context variables for anything else. If I include a panel template with an include tag, I will have to write these requests in all the views containing the panel and pass them as context variables.

Alternatively, I could write a special inclusion tag containing requests and pass them to the panel template. Using a special inclusion tag, I will not need to repeat the code to create its context in all views containing the panel. My views will contain less code and will be less cluttered context variables used only by the panel.

Although you're right in the sense that a custom inclusion tag that simply passes an unmanipulated context will be the same as an include tag.

+11
source share

Do I need to separate templates to smaller files? Use the include tag (for readability and maintenance and DRY)

Do I need to add more code before rendering the template? Use inclusion tags (fetching additional data, adding business logic). It really looks like another little view without a url. This is similar to a template function).

+4
source share

Basically, the point given by dgel and YardenST answers is correct. Also, looking at django code gives a good idea of ​​how these two options compare in performance.

When using the default template loaders , there is no difference between the two. Both end up calling the InclusionTag render() function, which in turn calls the Loader get_contents() template call, which opens the template file from the file system. render() only caches the file if it is used in a template for a loop.

As a side note, a performance difference would be possible using django.template.loaders.cached.Loader .

Finally, regarding the dgel proposal to use the inclusion tag for the general context in different views: it is very possible to avoid small additional overhead when rendering the inclusion template when the html markup is in one basic template that spans many views using ContextMixin . This is a fairly common script for rendering, for example. main menu in the basic template.

0
source share

All Articles