Loading [MathJax]/jax/output/HTML-CSS/config.js

Good,True and Beautiful

Good Good Study, Day Day Up

导航

< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8

统计

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': '<{% %}> %% {%{ }%}'})

参考官方文档

  1. template: templates function
  2. SimpleTemplate: simpletemplate syntax
  3. examples: template page example

posted on   Simple Love  阅读(2257)  评论(0编辑  收藏  举报

编辑推荐:
· DeepSeek 解答了困扰我五年的技术问题
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 用 C# 插值字符串处理器写一个 sscanf
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
阅读排行:
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· DeepSeek 解答了困扰我五年的技术问题。时代确实变了!
· 本地部署DeepSeek后,没有好看的交互界面怎么行!
· 趁着过年的时候手搓了一个低代码框架
· 推荐一个DeepSeek 大模型的免费 API 项目!兼容OpenAI接口!
点击右上角即可分享
微信分享提示