mpe*_*pen 7 python django django-templates
假设我的模板里面有类似的东西,{% block subject %}my subject{% endblock %}并且我加载了这个模板tmpl = loader.get_template('mytemplate.html'),我怎样才能提取"我的主题"?
当您的模板扩展基础时,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)
我真的不确定这是否是以递归方式迭代所有节点的正确方法......但它在我的有限情况下有效.
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
自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)