Вы можете написать custom tag принять переменную построить имя шаблона во время выполнения ..
Следующий подход задействует функцию string.format
построить динамическое имя шаблона, он может иметь некоторые проблемы, когда вам необходимо пройти более двух переменных для форматирования имени шаблона, поэтому вам может потребоваться изменить и настроить следующий код для выполнения вашего требования.
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
Использование в шаблоне:
<!-- 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 %}
Это может помочь вам: http://stackoverflow.com/questions/21483003/replacing- a-character-in-django-template – jape