Python模板引擎 [英] Python template engine

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

问题描述

如果有人可以帮助我开始编写 Python 模板引擎,是否有可能?我是 Python 新手,在学习这门语言的过程中,我设法编写了一个小型 MVC 框架,该框架在其自己的轻量级 WSGI 式服务器中运行.

Could it be possible if somebody could help me get started in writing a python template engine? I'm new to python and as I learn the language I've managed to write a little MVC framework running in its own light-weight-WSGI-like server.

我设法编写了一个脚本来查找和替换值的键:(显然这不是我的脚本的结构或实现方式.这只是一个例子)

I've managed to write a script that finds and replaces keys for values: (Obviously this is not how my script is structured or implemented. this is just an example)

from string import Template

html  = '<html>\n'
html += '  <head>\n'
html += '  <title>This is so Cool : In Controller HTML</title>\n'
html += '  </head>\n'
html += '  <body>\n'
html += '    Home | <a href="/hi">Hi ${name}</a>\n'
html += '  </body>\n'
html += '<html>'

Template(html).safe_substitute(dict(name = 'Arturo'))

我的下一个目标是实现自定义语句、修饰符、函数等(如for"循环),但我真的不知道是否应该使用我不知道的另一个模块.我想到了正则表达式,但我觉得这不是一种有效的方法

My next goal is to implement custom statements, modifiers, functions, etc (like 'for' loop) but i don't really know if i should use another module that i don't know about. I thought of regular expressions but i kind feel like that wouldn't be an efficient way of doing it

感谢任何帮助,我相信这对其他人也有用.

Any help is appreciated, and i'm sure this will be of use to other people too.

谢谢

推荐答案

Python 支持许多强大的模板语言.我更喜欢 Jinja2.另请查看 Mako元始.

There are many powerful template languages supported by Python out there. I prefer Jinja2. Also take a look at Mako and Genshi.

Mako 是三个中最快的,但它的意识形态允许在模板中拥有复杂的代码逻辑,这会不时引发违反 MVC 原则的行为.

Mako is fastest among three, but it's ideology allows to have a complex code logic right in template that provoke MVC principles violation from time to time.

Genshi 有很好的构思,特别强大的特性是反向模板继承.但它是三个中最慢的,而且实践表明,它的所有功能在实际项目中往往都是过大的.

Genshi has excellent conception, especially powerful feature is inversed template inheritance. But it is slowest among three and as practice shows all its features are often overkill in real project.

在我个人看来,Jinja2 是一个黄金中间.由于它使用类似于 Django 模板和 Liquid 模板语言的语法,因此它很容易扩展,速度很快,而且很多人都很熟悉.

Jinja2 is a golden middle in my personal opinion. It is easily extensible, quite fast and familiar to many since it use syntax similar to Django templates and Liquid template language.

这篇关于Python模板引擎的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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