bottlepy template
bottle template usage
1 example
使用bottle模板,最简单的方法是使用template
函数或view
装饰器
1.1 template 函数
例子如下:
from bottle import template
template('filename', name="hello world") # filename 为文件名可以不包括后缀,默认后缀有:['tpl','html','thtml','stpl']
或
template('hello {{name}}', name="world") # 第一个参数也可以直接为字符串内容
# 或 定制其他参数
template('form.html', template_lookup=['./template/'], template_settings={'noescape':1}, data=json.dumps(data))
# 完整例子
from bottle import template, route
@route('/')
def index():
return template('index', name="world") # 返回 str(或python2 中的unicode)
### index.tpl
hello {{name}}
###
在bottle中可以使用的模板引擎有: MakoTemplate
,CheetahTemplate
,Jinja2Template
,SimpleTemplate
; 版本0.12.9中默认使用SimpleTemplate
可以在template
中通过参数template_adapter
来指定其他引擎, 也可以直接使用mako_template
,cheetah_template
,jinja2_template
函数
默认查找路径 bottle.TEMPLATE_PATH
即 ['./', './views/']
, 我们可以通过template_lookup参数来修改搜索路径
另外也可以通过参数template_settings
来控制模板引擎渲染,比如在输出JSON数据时,不希望进行HTML ESCAPE, 则在SimpleTemplate中可以指定noescape
为True
1.2 view
装饰器
# 和使用 template 一样
@view('hello_template')
def hello(name='World'):
return dict(name=name)
2.2 SimpleTemplate
引擎语法
变量和函数调用
% name = "Bob" # a line of python code
<p>Some plain text in between</p>
<%
# A block of python code
name = name.title().strip()
%>
<p>More plain text</p>
循环
<ul>
% for item in basket:
<li>{{item}}</li>
% end
</ul>
条件控制
<div>
% if True:
<span>content</span>
% end
</div>
默认模板语法使用语法符号为 <% %> % {{ }}
,为了不与angularjs或underscore等前端模板冲突, 我们可以修改模板语法 如 <{% %}> %% {%{ }%}
语法由空白字符分割,共5部分组成: block_start block_close line_start inline_start inline_end
template('filename', template_settings={'syntax': '<{% %}> %% {%{ }%}'})
参考官方文档
- template: templates function
- SimpleTemplate: simpletemplate syntax
- examples: template page example
posted on 2016-10-23 21:28 Simple Love 阅读(2257) 评论(0) 编辑 收藏 举报
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 解答了困扰我五年的技术问题
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 用 C# 插值字符串处理器写一个 sscanf
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· DeepSeek 解答了困扰我五年的技术问题。时代确实变了!
· 本地部署DeepSeek后,没有好看的交互界面怎么行!
· 趁着过年的时候手搓了一个低代码框架
· 推荐一个DeepSeek 大模型的免费 API 项目!兼容OpenAI接口!