简体   繁体   English

使用Jinja2自定义模板

[英]Custom templating using Jinja2

I am trying to use jinja2 as follows. 我正在尝试使用jinja2如下。

Suppose, 假设,

Following are tags: 以下是标签:

tags: {"world":"WORLD", "c language": "Dennis Ritchie", "apple":"JOBS" }

Input: 输入:

HELLO {{ world }}, C is written by **{{ c language }}**, **}}** while **{{** java is written by {{ java }}, hola.

Output: 输出:

HELLO WORLD, C is written by Dennis Ritchie, **}}** while **{{** java is written by, hola.

So in short there are following things I have to do. 简而言之,我需要做以下事情。

  1. delimiters - {{ & }} 分隔符-{{&}}
  2. If there is no tag predefined, it should put empty. 如果没有预定义的标签,则应将其置空。
  3. If there is only single delimiter {{ or }} ( I mean not pair) ,it should not consider tag else it should be printed as it it. 如果只有单个定界符{{或}}(我的意思是不成对),则不应考虑标签,否则应将其打印出来。
  4. Tags should allow spaces. 标签应留有空格。

Out of 4, for only 1 & 2 jinja2 is working fine. 在4中,只有1&2 jinja2可以正常工作。

from jinja2 import Template
t = Template(input_string)
t.render(context)

But for 3rd & 4th, it's not working.(or I am mistaking.) 但是对于第三和第四,它不起作用(或者我误会了。)

I found only 1 template engine called "mustache" which supports above all 4 conditions. 我发现只有1个模板引擎称为“ mustache”,它支持上述所有4种条件。 But I don't know how it works in case of performance. 但是我不知道它在性能方面如何工作。

As jinja2 is mature template engine, I think it's possible to customize default behaviour. 由于jinja2是成熟的模板引擎,我认为可以自定义默认行为。

Can anybody know solution? 有人知道解决办法吗?

Thnx in advance. 提前thnx。

My primary testing shows that Mustache(Pystache) is too faster than jinja2. 我的主要测试表明,Mustache(Pystache)比jinja2快。 If possible please give expert opinion. 如果可能,请给出专家意见。

http://mustache.github.io/ http://mustache.github.io/

https://github.com/defunkt/pystache https://github.com/defunkt/pystache

Finally I continue with mustache . 最后我继续留胡子 It's really awesome template engine. 这真的是很棒的模板引擎。

http://mustache.github.io/ http://mustache.github.io/

For mustache build for python 对于python的胡须构建

https://github.com/defunkt/pystache https://github.com/defunkt/pystache

I don't think this is possible. 我认为这是不可能的。 The documentation is quite clear on identifiers: 文档对标识符非常清楚:

Jinja2 uses the regular Python 2.x naming rules. Jinja2使用常规的Python 2.x命名规则。 Valid identifiers have to match [a-zA-Z_][a-zA-Z0-9_]*. 有效标识符必须匹配[a-zA-Z _] [a-zA-Z0-9 _] *。 As a matter of fact non ASCII characters are currently not allowed. 实际上,当前不允许使用非ASCII字符。 This limitation will probably go away as soon as unicode identifiers are fully specified for Python 3. 为Python 3完全指定unicode标识符后,此限制可能会消失。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM