Django:我如何从模板中获取块?

mpe*_*pen 7 python django django-templates

假设我的模板里面有类似的东西,{% block subject %}my subject{% endblock %}并且我加载了这个模板tmpl = loader.get_template('mytemplate.html'),我怎样才能提取"我的主题"?

mpe*_*pen 6

当您的模板扩展基础时,Camilo的解决方案不起作用.我已经修改了一下(希望)解决了这个问题:

from django.template import Context
from django.template.loader import get_template
from django.template.loader_tags import BlockNode, ExtendsNode

def _get_node(template, context=Context(), name='subject'):
    for node in template:
        if isinstance(node, BlockNode) and node.name == name:
            return node.render(context)
        elif isinstance(node, ExtendsNode):
            return _get_node(node.nodelist, context, name)
    raise Exception("Node '%s' could not be found in template." % name)
Run Code Online (Sandbox Code Playgroud)

我真的不确定这是否是以递归方式迭代所有节点的正确方法......但它在我的有限情况下有效.

  • 我把这个片段带到了下一个级别,并使其更加广泛地使用递归模板 - https://github.com/bradwhittington/django-templated-email/blob/867ef61693d02a39ca902a30e66d5dd7dd941cda/templated_email/utils.py它打破/丢失信息如果您在继承的模板中使用{{block.super}}.很高兴接受修复,使其更完整 (4认同)

Cam*_*pka 5

from django.template import Context
from django.template.loader import get_template
from django.template.loader_tags import BlockNode

t = get_template('template.html')
for node in t:
    if isinstance(node, BlockNode) and node.name == 'subject':
        print node.render(Context())
Run Code Online (Sandbox Code Playgroud)

这对我有用,使用Django 1.1.1


mik*_*ser 5

Django 1.8以来,建议的答案不起作用:

在Django 1.8中更改:get_template()返回依赖于后端的模板而不是django.template.Template.

新的django.template.backends.django.Template不可迭代,因此for循环会给出错误:

'Template'对象不可迭代.

使用Django模板系统的解决方案(基于@CamiloDíazRepka答案):

from django.template import Context
from django.template.loader import get_template
from django.template.loader_tags import BlockNode

t = get_template('template.html')
for node in t.template:
    if isinstance(node, BlockNode) and node.name == 'subject':
        print node.render(Context())
Run Code Online (Sandbox Code Playgroud)