问题描述
免责声明:这是从。
我试图在Django中编写一个模板标签,这将在Mako模板的身体。我不知道这是可以实现的,但这对我的项目来说非常有用,也有很多其他人在Django中使用Mako模板。
I'm attempting to write a template tag in Django, that will render itself within the body of a Mako Template. I'm not sure that this is achievable, but it's something that'd be extremely useful to my project, and probably a lot of other people using Mako Templates within Django.
这是我的标签的定义:
def extends_mako(parser, token):
# wishlist below, this code does not work but it's what I want to achieve
template_html = ''
while (node = parser.nodelist.pop()):
template_html += node.render()
解析器对象能够渲染整个树到此为止吗?我目前唯一的想法是使用解析器对象来渲染(并从树中删除)之前的每一个节点。然后我将输出传递给Mako,作为HTML呈现,并将其用作我定义的节点的render函数的输出。我希望的是,当在模板上调用render时,只需要渲染一个节点,因为我的模板标签已经完成了其他所有的编译。目的是将extend_mako标签作为树中的最终标签。
Is the parser object capable of rendering the entire tree up to this point? My only idea at the moment, is to use the parser object to render (and remove from the tree) every node preceding this one. I'd then pass the output to Mako to render as HTML, and use that as the output to the render function of the Node I'm defining. My hope, is that when render is called on the template, it will only need to render this one node, since my template tag has already done the compilation on everything else. The intention is to have the extends_mako tag as the final tag in the tree.
我已经做了一些快速的pdb.set_trace调查,但是我看不到任何帮助到目前为止。
I've done some quick pdb.set_trace investigation, but I can't see anything that helps thus far.
所以;可以使用解析器对象,传递给模板标签,编译模板,并检索最终的渲染输出?
So; Is it possible to use the parser object, passed to the template tag, to compile the template, and retrieve the final rendered output?
推荐答案
p>这不是一个特定于您的问题的解决方案,但可能会让您处于正确的方向。我最近采用了Django的无空格模板标签,并添加了支持,以便在调试时无法删除空白。
This isn't a solution specific to your problem, but might get you in the right direction. I recently took Django's "spaceless" template tag and added support to not strip the whitespace out when debugging.
该模板标签的一部分传递了{%spaceless%} {%endspaceless%}标签,理论上可能会让您成为节点之前的节点...
Part of that template tag passes the list of template nodes collected between the {% spaceless %}{% endspaceless %} tags, which in theory, might get you the nodes preceeding your node...
from django.conf import settings
from django import template
from django.utils.html import strip_spaces_between_tags
register = template.Library()
class SmartSpacelessNode(template.Node):
def __init__(self, nodelist):
self.nodelist = nodelist
def render(self, context):
content = self.nodelist.render(context)
#from here, you can probably delete the nodes after you've rendered
#the content to a variable, then render your tag
return content if settings.DEBUG else strip_spaces_between_tags(content.strip())
@register.tag
def smart_spaceless(parser, token):
nodelist = parser.parse(('end_smart_spaceless',))
parser.delete_first_token()
return SmartSpacelessNode(nodelist)
希望能帮助你。
这篇关于如何在django中的模板标签中获取模板的渲染输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!