How to do it...

Advanced custom template tags consist of two things:

  • A function that parses the arguments of the template tag
  • The Node class that is responsible for the logic of the template tag as well as the output

Perform the following steps to create the {% try_to_include %} template tag:

  1. First, let's create the function parsing the template tag arguments, as follows:
# utils/templatetags/utility_tags.py
from django import template
from django.template.loader import get_template

register = template.Library()


"""TAGS"""


@register.tag
def try_to_include(parser, token):
"""
Usage: {% try_to_include "sometemplate.html" %}

This will fail silently if the template doesn't exist.
If it does exist, it will be rendered with the current context.
"""
try:
tag_name, template_name = token.split_contents()
except ValueError:
tag_name = token.contents.split()[0]
raise template.TemplateSyntaxError(
f"{tag_name} tag requires a single argument")
return IncludeNode(template_name)
  1. Then, we need a custom IncludeNode class in the same file, extending from the base template.Node, as follows:
# utils/templatetags/utility_tags.py
# ...
class IncludeNode(template.Node):
def __init__(self, template_name):
self.template_name = template.Variable(template_name)

def render(self, context):
try:
# Loading the template and rendering it
included_template = self.template_name.resolve(context)
if isinstance(included_template, str):
included_template = get_template(included_template)
rendered_template = included_template.render(context)
except (template.TemplateDoesNotExist,
template.VariableDoesNotExist,
AttributeError):
rendered_template = ""
return rendered_template
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.253.221