March 2020
Intermediate to advanced
608 pages
17h 17m
English
Perform the following steps to create the {% try_to_include %} template tag:
# myproject/apps/core/templatetags/utility_tags.pyfrom django import templatefrom django.template.loader import get_templateregister = template.Library()""" TAGS """@register.tagdef try_to_include(parser, token): """ Usage: {% try_to_include "some_template.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" ...