[Answered ]-Using context variables inside text inside template tag in django

2👍

You can write a custom tag to accept variable to build a template name in runtime..

The following approach is leveraging the string.format function to build a dynamic template name, it may have some issues when you need to pass more than two variable to format the template name, so you may need amend and customise the following code to fulfil your requirement.

your_app_dir/templatetags/custom_tags.py

from django import template
from django.template.loader_tags import do_include
from django.template.base import TemplateSyntaxError, Token


register = template.Library()


@register.tag('xinclude')
def xinclude(parser, token):
    '''
    {% xinclude "blogs/blog{}.html/" "123" %}
    '''
    bits = token.split_contents()
    if len(bits) < 3:
        raise TemplateSyntaxError(
            "%r tag takes at least two argument: the name of the template to "
            "be included, and the variable" % bits[0]
        )
    template = bits[1].format(bits[2])
    # replace with new template
    bits[1] = template
    # remove variable
    bits.pop(2)
    # build a new content with the new template name
    new_content = ' '.join(bits)
    # build a new token,
    new_token = Token(token.token_type, new_content)
    # and pass it to the build-in include tag
    return do_include(parser, new_token)  # <- this is the origin `include` tag

Usage in your template:

<!-- load your custom tags -->
{% load custom_tags %}

<!-- Include blogs/blog123.html -->
{% xinclude "blogs/blog{}.html" 123 %}

<!-- Include blogs/blog456.html -->
{% xinclude "blogs/blog{}.html" 456 %}

Leave a comment