我想在我的模板中做这样的事情。在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