Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Built-in include tag vs custom inclusion tag

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

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

like image 209
gjb Avatar asked Jan 08 '13 15:01

gjb


2 Answers

They serve different purposes. The include tag simply includes the content from an existing template in its entirety and unmodified. A custom inclusion tag passes the context to a function which can contain logic to manipulate the context before passing it to a template.

For example, perhaps I have a panel that will be shown on multiple pages. The panel's template requires a few specific queries to be passed to it through the context. The pages that contain the panel don't require those context variables for anything else. If I include the panel template with the include tag, I would have to write those queries in every view that contains the panel and pass them as context variables.

Alternatively, I could write a custom inclusion tag that contains the queries and passes them to the panel's template. By using the custom inclusion tag I wouldn't need to repeat the code to produce its context in every view that contains the panel. My views would contain less code and would be less cluttered with context variables only used by the panel.

Although you are correct in the sense that a custom inclusion tag that simply passes on the context unmanipulated would be the same as the include tag.

like image 116
dgel Avatar answered Sep 20 '22 17:09

dgel


Need to separate templates to smaller files? Use include tag (for readability and maintainability and DRY)

Need to include more code before rendering the template? Use inclusion tags (fetch more data, add some business logic.. it is really like another small url-less view. it is like a template function).

like image 36
YardenST Avatar answered Sep 22 '22 17:09

YardenST