码迷,mamicode.com
首页 > Web开发 > 详细

详解Bottle模板

时间:2016-08-28 22:53:43      阅读:2617      评论:0      收藏:0      [点我收藏+]

标签:

今天和大家分享一下自己在学习Bottle框架的过程中总结的关于模板的知识点,希望对大家有帮助。

Bottle 使用自带的小巧的模板。
你可以使用调用 template(template_name, **template_arguments) 并返回结果。

@route(’/hello/:name’)def hello(name):

    return template(’hello_template’, username=name)

这样就会加载 hello_template.tpl,并提取 URL:name 到变量 username,返回请求。

hello_template.tpl 大致这样:

<h1>Hello {{username}}</h1><p>How are you?</p>

 

模板搜索路径

模板是根据 bottle.TEMPLATE_PATH 列表变量去搜索。
默认路径包含 [’./%s.tpl’, ’./views/%s.tpl’]

 

模板缓存

模板在编译后在内存中缓存。
修改模板不会更新缓存,直到你清除缓存。
调用 bottle.TEMPLATES.clear()

 

模板语法

模板语法是围绕 Python 很薄的一层。
主要目的就是确保正确的缩进块。


下面是一些模板语法的列子:

%...Python 代码开始。不必处理缩进问题。Bottle 会为你做这些。

%end 关闭一些语句 %if ...%for ... 或者其他。关闭块是必须的。

{{...}} 打印出 Python 语句的结果。

%include template_name optional_arguments 包括其他模板。

每一行返回为文本。

Example:

%header = ’Test Template’

%items = [1,2,3,’fly’]

%include http_header title=header, use_js=[’jquery.js’, ’default.js’]

<h1>{{header.title()}}</h1>

<ul>

%for item in items:

  <li>

    %if isinstance(item, int):

      Zahl: {{item}}

    %else:

      %try:

        Other type: ({{type(item).__name__}}) {{repr(item)}}

      %except:

        Error: Item has no string representation.

      %end try-block (yes, you may add comments here)

    %end

    </li>

  %end

</ul>

%include http_footer

 

 

文章来自:segmentfault

详解Bottle模板

标签:

(1)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
jiangjie190
加入时间:2016-02-19
  关注此人  发短消息
文章分类
jiangjie190”关注的人------(0
jiangjie190”的粉丝们------(0
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!