custom inclusion_tag vs built-in include tag django

custom inclusion_tag vs built-in include tag django

 Advantages using inclusion tags:

  • If we observe the templates of website we can see the repetitive code or components.
  • We can take repetitive code/component in a partial template and include it in other templates wherever the code is required.
  • We use inclusion tags (include tag,  custom inclusion_tag) for cases like navigation menu, search forms, headers, footers, etc.
  • In future we may want to change our website / webapp structure (navigation menu or header, footer) then we don't need to change it in every template but have to change it in partial template that is included in other pages.
  • This will improve the maintainability of templates.

 built-in include tag:

  • It is the django's built-in template tag.
  • Include tag it simply takes the partial template name as a string("partial/nav_menu.html") and uses the context passed from the view to render and include the partial template in the main template.
  • We can also pass the extra context to Include tag using keyword arguments.
  • Use Include tag only when we don't need to process the context data.
  • It is simple and most used template tag in django.

 custom inclusion_tag:

  • custom inclusion_tag works same as include tag.
  • The only difference between custom inclusion tag and include tag is we can process the context data and render the template with processed context data.

It's coding time

  • In above code I have passed dummy data for "pk" and "name" as extra context data in built-in include tag. In general we get it from template tags.
  • If you don't want to use the context in custom inclusion tag you can set "takes_context=False" (default value is False if we don't provide)

Buy a product to Support me

-->