mako模板基础

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/baidu_35085676/article/details/80560847

mako模板算是Python里面比较出色的一个模板了,它宣称有比Jinja2更快的解析速度已经更多的语法支持,本篇博客对它的使用做一个小结。

安装

使用pip可以方便的安装

# 无需root权限,安装到用户目录下 
pip install mako --user #python2
pip3 install mako --user #python3

使用

Template

通过from mako.template import Template引入mako模板,最基础的用法是这样:

from mako.template import Template
t = Template("Hello,${name}")
print(t.render(name = 'world'))

==>Hello,world

Template函数还有一些常用的参数:

filename:指定从文件中加载模板。最好用相对路径,否则缓存文件会包含在很长的路径下。
module_directory:缓存目录。从文件中加载模板,可以指定module_directory生成.py文件缓存,提高加载速度。

TemplateLookup

一般来说,我们不直接使用Template,而是使用TemplateLookup。
TemplateLookup可以给一系列模板预设参数,方便使用:
base

this is the base templent!

index.html

<%include file="base"/>
Hello ${name}!
lookup = TemplateLookup(directories['tt'],module_directory=ROOT_DIR+'/tt',collection_size=500,filesystem_checks=True)
tf = lookup.get_template('index.html')
print(tf.render(name='init'))
# 使用templateLookup,可以方便的设置模板目录,当模板中include别的模板时可以只写模板名
# collection_size设置加载到内存中的模板上限
# filesystem_checks为True会在每次加载模板缓存判断模板文件是否有改动,会重新编译。
==》this is the base templent!
==》Hello,init

语法

变量

${name}
{}中可以执行Python语句,比如${name.upper()}会转为大写

注释

##后面根单行注释

<%doc>
多行注释
</%doc>

此外注意若模板中存在中文应指点个编码,使用## coding=utf-8

循环

% for i in l:
    ${i}
% endfor

条件

% if i == 1:
    ${i}
% end if

任意Python语句

# <% 两个标签之内的是执行的任意Python语句 %>
<%
x = 'lyt'
x.upper()
%>
${x}

猜你喜欢

转载自blog.csdn.net/baidu_35085676/article/details/80560847