Python Mako笔记
2016-06-20 12:33
417 查看
译自 http://docs.makotemplates.org/en/latest/usage.html#basic-usage
BasicUsage
最基本的是用Template类
from
mako.template
import Template
mytemplate = Template("hello world!")
print(mytemplate.render())
以上,文本参数被编译为一个python模块对象。这个模块有个render_body()函数,产生模板的输出。当调用mytemplate_render()函数,Mako为模板建立一个运行环境并且调用render_body()函数,将输出存入缓存并返回字符串内容。
render_body()内的函数有一些变量的命名空间,你可以通过传递参数指定这些变量。
from
mako.template
import Template
mytemplate = Template("hello, ${name}!")
print(mytemplate.render(name="jack"))
render()方法调用Mako创建Context对象,其中存储模板中变量的名字并且有存放输出的缓存。你可以自己创建Context对象,用render_context()方法。
from
mako.template
import Template
from mako.runtime
import Context
from StringIO
import StringIO
mytemplate = Template("hello, ${name}!")
buf = StringIO()
ctx = Context(buf, name="jack")
mytemplate.render_context(ctx)
print(buf.getvalue())
UsingFile-Based Templates
也可以从文件中获取模板,用filename参数。
from
mako.template
import Template
mytemplate = Template(filename='/docs/mytmpl.txt')
print(mytemplate.render())
为了改进性能,从文件载入的模板也可以缓存为python模块,只需要增加module_directory参数。
from
mako.template
import Template
mytemplate = Template(filename='/docs/mytmpl.txt',
module_directory='/tmp/mako_modules')
print(mytemplate.render())
下次创建相同参数的模板时,就会自动重用这个模块文件。
UsingTemplateLookup
BasicUsage
最基本的是用Template类
from
mako.template
import Template
mytemplate = Template("hello world!")
print(mytemplate.render())
以上,文本参数被编译为一个python模块对象。这个模块有个render_body()函数,产生模板的输出。当调用mytemplate_render()函数,Mako为模板建立一个运行环境并且调用render_body()函数,将输出存入缓存并返回字符串内容。
render_body()内的函数有一些变量的命名空间,你可以通过传递参数指定这些变量。
from
mako.template
import Template
mytemplate = Template("hello, ${name}!")
print(mytemplate.render(name="jack"))
render()方法调用Mako创建Context对象,其中存储模板中变量的名字并且有存放输出的缓存。你可以自己创建Context对象,用render_context()方法。
from
mako.template
import Template
from mako.runtime
import Context
from StringIO
import StringIO
mytemplate = Template("hello, ${name}!")
buf = StringIO()
ctx = Context(buf, name="jack")
mytemplate.render_context(ctx)
print(buf.getvalue())
UsingFile-Based Templates
也可以从文件中获取模板,用filename参数。
from
mako.template
import Template
mytemplate = Template(filename='/docs/mytmpl.txt')
print(mytemplate.render())
为了改进性能,从文件载入的模板也可以缓存为python模块,只需要增加module_directory参数。
from
mako.template
import Template
mytemplate = Template(filename='/docs/mytmpl.txt',
module_directory='/tmp/mako_modules')
print(mytemplate.render())
下次创建相同参数的模板时,就会自动重用这个模块文件。
UsingTemplateLookup
相关文章推荐
- 【Python】 sorted函数
- django,python,svn_web
- python 安装easy_install和pip
- python argparse模块的简单使用
- python步进切片
- Python目录树
- python修改txt文件内容
- python类的简单定义
- mac 安装reportlab工具
- eval的使用问题
- python 程序列表
- SQlite保存python的对象
- python中pdb调试使用
- python 进程信息
- 在 Visual Studio 上更好开发 Python 的六大功能!
- python 读取机器信息
- python 时间及日期函数
- C扩展python的module和Type
- 安装 mysql - python
- python之set(集合)简介