mako模板基础

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}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值