包含之后的Jinja2编译扩展 [英] Jinja2 compile extension after includes
问题描述
在Jinja2中,是否可以在所有include
语句完成后从AST渲染中获取Node
?
In Jinja2, is it possible to have a Node
from the AST render after all include
statements have completed?
这是关键的的一个关键解决方案一个更大的难题.
示例代码:
from jinja2 import nodes, Environment, FileSystemLoader
from jinja2.ext import Extension
class XExtension(Extension):
tags = set(['x', 'get_x'])
def __init__(self, environment):
super(XExtension, self).__init__(environment)
environment.extend(
x = 0,
)
def parse(self, parser):
tag = parser.stream.next()
return getattr(self, "_%s" % str(tag))(parser, tag)
def _get_x(self, parser, tag):
""" Return the output """
return nodes.Const(self.environment.x)
def _x(self, parser, tag):
""" Add an x """
self.environment.x += 1
return nodes.Const('<!-- Adding an X -->')
env = Environment(
loader = FileSystemLoader('.'),
extensions = [XExtension],
)
template = env.get_template('x.html')
print template.render()
x.html
Xx {% x %} Xx {% x %}
{% include "y.html" %}
Xs xes: {% get_x %}
y.html
Yx {% x %}
Ys xes: {% get_x %}
输出为
Xx <!-- Adding an X --> Xx <!-- Adding an X -->
Yx <!-- Adding an X -->
Ys xes:3
Xs xes 2
Xs xes
如何计算y.html
中的X,这是我期望和期望的行为?
How may it be possible to have Xs xes
count the X's in y.html
, which is the behaviour I desire and expect?
换句话说,是否有一种方法可以延迟对x.html
中从_get_x()
返回的文本的解析或扁平化?
In other words, is there a way to delay the parsing or flattening to text returned from the _get_x()
in x.html
?
非常感谢您阅读.
亲切的问候,
布莱恩
推荐答案
Jinja2进行模板数据流传输.对模板进行评估后的指令用于将指令输入到较小的字符串流中,该较小的字符串流通过render()
方法连接为实际的unicode字符串.但是,您也可以通过调用generate()
而不是render()
来获取流.
Jinja2 does streaming of template data. The template is evaluated instruction for instruction into a stream of smaller strings that gets concatenated into an actual unicode string by the render()
method. However you can also get hold of the stream by calling into generate()
instead of render()
.
使用流中的某些带内信令和后处理功能,也许可以实现类似的功能,但这与Jinja2的设计方式背道而驰,因此可能会严重破坏并且完全不受支持.
With some in-band signalling and postprocessing of the stream one might probably be able to implement something like that, but it's against the way of how Jinja2 was designed so it might break horribly and is totally unsupported.
这篇关于包含之后的Jinja2编译扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!