【问题标题】:Using context variables inside text inside template tag in django在 django 的模板标签内的文本中使用上下文变量
【发布时间】:2017-02-14 22:54:14
【问题描述】:

我想在我的模板中做这样的事情。

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

XYZ 部分应该是可变的。即我怎样才能将上下文变量传递给这个位置。例如,如果我正在阅读第一个博客,我应该能够包含 blog1.html。如果我正在阅读第二篇博客,我应该能够包含 blog2.html 等等。在 django 中可以吗?

【问题讨论】:

标签: django django-templates templatetags


【解决方案1】:

您可以写一个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" %}
猜你喜欢
  • 2014-01-15
  • 1970-01-01
  • 1970-01-01
  • 2016-12-25
  • 2018-06-05
  • 2012-02-18
  • 2021-06-02
  • 2011-08-27
相关资源
最近更新 更多