zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    【转】java对File.listFiles()排序
    java 获取当前目录文件名
    python批量创建文件夹
    [好课推荐]数据结构与算法python实现
    SCI论文重复率与降重
    [转]一图搞定Matplotlib
    [GitHub寻宝]机器学习实战python3代码分享
    [好课推荐]人工智能实践:Tensorflow2.0
    [转]用深度学习给黑白照片上色
    java split函数分割字符串
  • 原文地址:https://www.cnblogs.com/i2u9/p/bottle-template.html
Copyright © 2011-2022 走看看