我想在我的模板中做這樣的事情。在django的模板標籤內使用上下文變量
{% include "blogs/blogXYZ.html" %}
XYZ部分應該是可變的。即我如何傳遞一個上下文變量到這個位置。例如,如果我正在閱讀第一篇博客,我應該可以包含blog1.html。如果我正在閱讀第二篇博客,我應該可以包含blog2.html等等。在Django中可能嗎?
我想在我的模板中做這樣的事情。在django的模板標籤內使用上下文變量
{% include "blogs/blogXYZ.html" %}
XYZ部分應該是可變的。即我如何傳遞一個上下文變量到這個位置。例如,如果我正在閱讀第一篇博客,我應該可以包含blog1.html。如果我正在閱讀第二篇博客,我應該可以包含blog2.html等等。在Django中可能嗎?
你可以寫一個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 %}
在新的模板名稱生成後,我們不能使用「return do_include(parser,template)」嗎?爲什麼要進一步處理位? –
這是因爲'xinclude'參數僅用於生成模板名稱,並且在構建模板名稱時不再需要param。換句話說,'xinclude'用於動態生成一個標籤:'{%include「blogs/blog123.html」%}' – Enix
這可以幫助你:http://stackoverflow.com/questions/21483003/replacing- a-character-in-django-template – jape