编译Jinja2 AST的小节 [英] Compile subsection of Jinja2 AST

查看:123
本文介绍了编译Jinja2 AST的小节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个人可以编译或还原Jinja2 AST的一部分吗?

Can one compile or revert a portion of the Jinja2 AST?

例如,是否可以从 jinja2.environment jinja2.compiler.generate 还是从模板中提取的节点列表中的等效项?

For example, is it possible to call a function or method from jinja2.environment or jinja2.compiler.generate or some equivalent on a list of nodes extracted from within a template?

例如,给定模板 y.html

avant-tag
{% xyz %}
tag content {{ 3 + 5 }}
{% endxyz %}
apres-tag

和扩展名 y.py

# -*- coding: utf-8 -*-
from jinja2 import nodes, Environment, FileSystemLoader
from jinja2.ext import Extension

class YExtension(Extension):
    tags = set(['y'])

    def __init__(self, environment):
        super(YExtension, self).__init__(environment)

    def parse(self, parser):
        tag = parser.stream.next()
        body = parser.parse_statements(['name:endy'], drop_needle=True)
        return nodes.Const("<!-- slurping: %s -->" % str(body))

env = Environment(
    loader      = FileSystemLoader('.'),
    extensions  = [YExtension],
    )

print env.get_template('x.html').render()

运行 python y.py 的预期输出为:

avant-tag
 <!-- slurping: [Output(nodes=[TemplateData(data=u'\n    tag-content '),
   Add(left=Const(value=3), right=Const(value=5)),
   TemplateData(data=u'\n ')])] -->
sous-tag

解析方法,怎么可能这样:

In the parse method, how can one either:


  1. body 编译为unicode(即标签内容8 );或者,或者

  2. body 还原为其原始来源(即 tag-content {{3 + 5} } )。

  1. compile body to unicode (i.e. tag-content 8); or, alternatively
  2. revert body to its original source (i.e. tag-content {{ 3 + 5 }}).

作为背景,该问题与两个先前的问题有关:

As a matter of background, this question relates to two prior questions:


  1. Jinja2编译扩展在包含之后;和

  2. 在Jinja 2中包含文件的顶部插入javascript

  1. Jinja2 compile extension after includes; and
  2. Insert javascript at top of including file in Jinja 2

感谢您阅读。

Brian

推荐答案

parse( )方法,因为此时您没有可用的上下文。当然,您可以修改它,但这可能不是最好的方法。

Compiling to unicode is not yet possible in the parse() method since you don't have the context available at that point. You can hack around it ofcourse but it would probably not be the best way to go.

请注意, parse() step通常只在html文件上执行一次,此后它将使用已解析的字节码呈现模板。可以在给定环境的情况下呈现解析步骤的结果。

Note that the parse() step is normally only executed once on a html file, after that it will use the parsed bytecode to render the template. The results of the parse step can be rendered given an environment.

您根本就没有可用的上下文,并且无法在其中获取上下文...相当困难;)

You simply don't have the context available there, and getting the context in there... quite difficult ;)

但是要获取原始资源...不进行黑客攻击就不会容易得多,但是黑客攻击还不是很糟糕;)

To get the original source however... not much easier without hacking, but the hacking isn't too bad ;)

class YExtension(Extension):
    tags = set(['y'])

    def preprocess(self, source, name, filename=None):
        # insert some code here that replaces '{% xyz %}foo bar{% endxyz %}'
        # with something like: '{% xyz %}foo bar{% raw %}foo bar{% endraw %}{% endxyz %}'
        return source

之后,您可以从 {%raw%} 节点读取文本,作为。请确保在此之后将其丢弃,否则它将显示在您的模板中。

After that you can read the text as the value from the {% raw %} node. Be sure to trash it after that or it will show in your template.

这篇关于编译Jinja2 AST的小节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆