How it works...

The {% try_to_include %} template tag expects one argument, that is, template_name. Therefore, in the try_to_include() function, we try to assign the split contents of the token only to the tag_name variable (which is try_to_include) and the template_name variable. If this doesn't work, a TemplateSyntaxError is raised. The function returns the IncludeNode object, which gets the template_name field, and stores it as a template Variable object for later use.

In the render() method of IncludeNode, we resolve the template_name variable. If a context variable was passed to the template tag, its value will be used here for template_name. If a quoted string was passed to the template tag, then the content within the quotes will be used for  included_template, whereas a string corresponding to a context variable will be resolved into its string equivalent for the same.

Lastly, we will try to load the template, using the resolved included_template string and render it with the current template context. If that doesn't work, an empty string is returned.

There are at least two situations where we could use this template tag:

  • When including a template whose path is defined in a model, as follows:
{% load utility_tags %} 
{% try_to_include object.template_path %}
  • When including a template whose path is defined with the {% with %} template tag somewhere high in the template context variable's scope. This is especially useful when you need to create custom layouts for plugins in the placeholder of a template in Django CMS:
{# templates/cms/start_page.html #}
{% with editorial_content_template_path=
"cms/plugins/editorial_content/start_page.html" %} {% placeholder "main_content" %} {% endwith %}

When the placeholder is filled, the context variable is then read and the template can be safely included, if available:

{# templates/cms/plugins/editorial_content.html #}
{% load utility_tags %}

{% if editorial_content_template_path %}
    {% try_to_include editorial_content_template_path %}
{% else %}
    <div>
        <!-- Some default presentation of
editorial content plugin --> </div> {% endif %}
The template tags in the previous snippet have been split across lines for legibility, but in practice, template tags must be on a single line, and so they cannot be split in this manner.
..................Content has been hidden....................

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