sudheesh ks
sudheesh ks

Reputation: 371

Using context variables inside text inside template tag in django

I want to do something like this in my template.

{% include "blogs/blogXYZ.html" %}

The XYZ part should be variable. ie how can I pass a context variable to this position. For example if I am reading 1st blog, I should be able to include blog1.html. If I am reading 2nd blog, I should be able to include blog2.html and so on. Is it possible in django?

Upvotes: 1

Views: 1143

Answers (1)

Enix
Enix

Reputation: 4579

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 %}

Upvotes: 2

Related Questions