search
HomeBackend DevelopmentPython TutorialPython Web开发模板引擎优缺点总结

做 Web 开发少不了要与模板引擎打交道。我陆续也接触了 Python 的不少模板引擎,感觉可以总结一下了。

一、首先按照我的熟悉程度列一下:

pyTenjin:我在开发 Doodle 和 91 外教时使用。
Tornado.template:我在开发知乎日报时使用。
PyJade:我在开发知乎日报时接触过。
Mako:我只在一个早期就夭折了的小项目里用过。
Jinja2:我只拿它做过一些 demo。

其他就不提了,例如 Django 的模板,据说又慢又难用,我根本就没接触过。

二、再说性能

很多测试就是弄个大循环什么的,很没技术含量。其实模板的渲染时间主要消耗在字符串处理上,包括拼接、编码、转义等,而循环测的则是 Python runtime 的性能。

所以我还是用实际的例子来测试吧,最终选择了 Doodle 的首页。它有几个子模板、几个循环、几个函数调用和很多个变量,具有一定代表性。考虑到 pyTenjin 以外的模板引擎不支持局部缓存,我就把用到缓存的侧边栏去掉了,只渲染主体部分。

渲染 1000 次的结果为:pyTenjin 耗时 0.65 秒,取消预处理后耗时 0.9 秒;Tornado.template 耗时 1.0 秒;Jinja2 耗时 1.1 秒。

测试代码有几百行,19 个文件,我就懒得列出来了。其他模板引擎也懒得测了。

@pyTenjin 的优势很明显,特别是它支持预处理。这个预处理的主要作用是把一些常量先编译好,渲染时就不用再处理了(因为已经变成字符串了);此外,有些功能可以静态地决定是否开启,而预处理可以把那些不需要的功能代码(主要是 if 分支)提前去掉。此外还能缓存任意代码段的渲染结果,在一段时间内无需重新渲染。
@Jinja2 比 Tornado.template 慢是我没想到的,好像与很多测试不符。
@Mako 预计和 Jinja2 差不多。它也能缓存代码段的渲染结果。
@PyJade 需要把 Jade 模板转成其他模板,且无缓存,预计会慢很多。

考虑到除 PyJade 外肯定不存在几倍的性能差距,所以挑个好用的即可。

三、最后说易用性

@pyTenjin 的优点是可以写任意 Python 代码。
缺点是标记比较复杂和独特,有 、#{...}、#{{...}}、{==...==}、{#==...==#}、${...}、${{...}}、{#=...=#} 和 {#==...==#} 这么多种,不过看上去还挺萌的。
由于使用了 符号,在 HTML 标签内部使用时,会阻碍编辑器进行语法解析。
另外,它的 tagattr() 方法在 expr 参数为 0 时当成了 True 来处理,需要改源码来修正,而它又没有开源项目可以提交 pull request。
而且它只有一个开发者,已经有一年多没更新了,活跃度明显不够。

@Tornado.template 的优点是与 Tornado 搭配还不错(毕竟是自带的),功能和性能都还行。
缺点是出错时很难定位到是哪写错了,而且与其他模板引擎相比,功能确实少了点(不过我还没遇到不够用的情况)。
另外,{% raw ... %} 写起来好麻烦。None 在输出时会显示成 None,而不是空字符串,导致写起来很累。
它输出的 HTML 代码是去掉头尾空格的,不过单独的 Python 代码行会显示成空行,看上去比较怪。

@Jinja2 的优点是功能多,定义了很多辅助函数,有 filter,也有内联的 if 表达式这种语法糖,写起来比较舒服。此外,它能够调整空白,这使得它输出的 HTML 比较好看。
缺点是学习成本较高,语法也不是纯 Python 了,甚至不能 import Python 模块和使用 [item for item in list if item] 这种列表解析表达式。
另一个严重的缺点是不能输出非 ASCII 的字符串, 遇到这种情况必须使用 unicode 类型,但要保证这点很麻烦。

@Mako 的优点是和 pyTenjin 一样可以写任意 Python 代码,又和 Jinja2 一样支持 filter(其实习惯了函数调用的话)。
缺点也是学习成本较高,语法比较复杂,对 HTML 编辑器不友好。

@PyJade 的优点是写起来最快(特别是对前端而言),没什么多余的东西。
缺点和 Jinja2 一样,更惨的是它几乎没有文档,而且最新的 release 版不可用,需要用开发版。

目前看来,我还是继续用 pyTenjin 算了,其他的要么不好用,要么学习成本比较高,而且多出来的功能感觉并不是非有不可的。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What are the alternatives to concatenate two lists in Python?What are the alternatives to concatenate two lists in Python?May 09, 2025 am 12:16 AM

There are many methods to connect two lists in Python: 1. Use operators, which are simple but inefficient in large lists; 2. Use extend method, which is efficient but will modify the original list; 3. Use the = operator, which is both efficient and readable; 4. Use itertools.chain function, which is memory efficient but requires additional import; 5. Use list parsing, which is elegant but may be too complex. The selection method should be based on the code context and requirements.

Python: Efficient Ways to Merge Two ListsPython: Efficient Ways to Merge Two ListsMay 09, 2025 am 12:15 AM

There are many ways to merge Python lists: 1. Use operators, which are simple but not memory efficient for large lists; 2. Use extend method, which is efficient but will modify the original list; 3. Use itertools.chain, which is suitable for large data sets; 4. Use * operator, merge small to medium-sized lists in one line of code; 5. Use numpy.concatenate, which is suitable for large data sets and scenarios with high performance requirements; 6. Use append method, which is suitable for small lists but is inefficient. When selecting a method, you need to consider the list size and application scenarios.

Compiled vs Interpreted Languages: pros and consCompiled vs Interpreted Languages: pros and consMay 09, 2025 am 12:06 AM

Compiledlanguagesofferspeedandsecurity,whileinterpretedlanguagesprovideeaseofuseandportability.1)CompiledlanguageslikeC arefasterandsecurebuthavelongerdevelopmentcyclesandplatformdependency.2)InterpretedlanguageslikePythonareeasiertouseandmoreportab

Python: For and While Loops, the most complete guidePython: For and While Loops, the most complete guideMay 09, 2025 am 12:05 AM

In Python, a for loop is used to traverse iterable objects, and a while loop is used to perform operations repeatedly when the condition is satisfied. 1) For loop example: traverse the list and print the elements. 2) While loop example: guess the number game until you guess it right. Mastering cycle principles and optimization techniques can improve code efficiency and reliability.

Python concatenate lists into a stringPython concatenate lists into a stringMay 09, 2025 am 12:02 AM

To concatenate a list into a string, using the join() method in Python is the best choice. 1) Use the join() method to concatenate the list elements into a string, such as ''.join(my_list). 2) For a list containing numbers, convert map(str, numbers) into a string before concatenating. 3) You can use generator expressions for complex formatting, such as ','.join(f'({fruit})'forfruitinfruits). 4) When processing mixed data types, use map(str, mixed_list) to ensure that all elements can be converted into strings. 5) For large lists, use ''.join(large_li

Python's Hybrid Approach: Compilation and Interpretation CombinedPython's Hybrid Approach: Compilation and Interpretation CombinedMay 08, 2025 am 12:16 AM

Pythonusesahybridapproach,combiningcompilationtobytecodeandinterpretation.1)Codeiscompiledtoplatform-independentbytecode.2)BytecodeisinterpretedbythePythonVirtualMachine,enhancingefficiencyandportability.

Learn the Differences Between Python's 'for' and 'while' LoopsLearn the Differences Between Python's 'for' and 'while' LoopsMay 08, 2025 am 12:11 AM

ThekeydifferencesbetweenPython's"for"and"while"loopsare:1)"For"loopsareidealforiteratingoversequencesorknowniterations,while2)"while"loopsarebetterforcontinuinguntilaconditionismetwithoutpredefinediterations.Un

Python concatenate lists with duplicatesPython concatenate lists with duplicatesMay 08, 2025 am 12:09 AM

In Python, you can connect lists and manage duplicate elements through a variety of methods: 1) Use operators or extend() to retain all duplicate elements; 2) Convert to sets and then return to lists to remove all duplicate elements, but the original order will be lost; 3) Use loops or list comprehensions to combine sets to remove duplicate elements and maintain the original order.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools