次のアプローチは、動的テンプレート名を構築するためにstring.format
機能を活用して、あなたが渡す必要があるとき、それはいくつかの問題が発生する可能性があり
...ランタイムにテンプレート名を構築するために、変数を受け入れるようにcustom tagを書くことができます2つ以上の変数を使用してテンプレート名を書式設定する必要があるため、要件を満たすために次のコードを修正してカスタマイズする必要があります。
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