Bottle 模板
使用 template 可以载入 html 文件,默认加载路径在 ./views/ 文件夹里,使用 bottle.TEMPLATE_PATH 可以修改默认模板文件的路径
from bottle import route, run, template
@route('/')
def index():
return template('index.tpl')
run(host='localhost', port=8080, debug=True)模板传参
在模板中使用 {{var}} 可以获取后台传递过来的参数。
@route('/')
def index():
return template('index.tpl', name='jmjc')
-- index.tpl --
{{name}}模板语法
使用 % 可以在模板中使用编程语法。
# 单行
% name = "Bob" # 定义一个 name 的变量
# 多行、必须以 end 结尾
% for item in basket:
<li>{{item}}</li>
% end
% if 条件:
<!-- 条件为真时显示的内容 -->
% else:
<!-- 条件为假时显示的内容 -->
% end
#转义
\%
\>%
include
include 可以在模板中引入分段的模板文件。
% include('header.tpl', title='Page Title') # 传递 title 参数到 header.tpl 模板文件
Page Content
% include('footer.tpl')rebase
处理 include 将模板分段引入,bottle 也支持模板继承,通过 rebase 函数。
<!-- ./views/base.tpl -->
<html>
<head>
<title>{{title or 'No title'}}</title>
</head>
<body>
{{!base}}
</body>
</html>
<!-- 继承 base.tpl 模板 -->
% rebase('base.tpl', title='Page Title') #
<p>Page Content ...</p> <!-- 这段内容会加载到 {{!base}} 里面 -->