Django:如何从模板中获取一个块? [英] Django: How can I get a block from a template?
本文介绍了Django:如何从模板中获取一个块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我的模板有一个类似于 {%block subject%}我的主题{%endblock%}
,我加载了这个模板与 tmpl = loader.get_template('mytemplate.html')
,我如何提取我的主题?
解决方案
当您的模板扩展基地时,Camilo的解决方案不起作用。我修改了一下(希望)解决这个问题:
from django.template import Context
pre>
from django.template.loader从django.template.loader_tags导入get_template
导入BlockNode,ExtendsNode
def _get_node(template,context = Context(),name ='subject'):
对于模板中的节点:$ b $ b如果isinstance(node,BlockNode)和node.name == name:
return node.render(context)
elif isinstance(node,ExtendsNode):
return _get_node(node.nodelist,context,name)
raise异常(Node%s在模板中找不到%name)
我真的不知道这是否是递归迭代所有节点的正确方法,但它在我的有限的情况下工作。
Suppose my template has in it something like
{% block subject %}my subject{% endblock %}
and I load this template withtmpl = loader.get_template('mytemplate.html')
, how can I extract "my subject"?解决方案Camilo's solution doesn't work when your template extends a base. I've modified it a bit to (hopefully) fix that problem:
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)
I'm really not sure if this is the right way to recursively iterate over all the nodes... but it works in my limited case.
这篇关于Django:如何从模板中获取一个块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文