zoukankan      html  css  js  c++  java
  • mako模板系统(一)

    python中的模板系统比较多,我比较喜欢用的是mako。

    mako模板的功能

    变量取代:

    ${}

    在里面可以执行python内建的函数,以及通过模板Context传递过来的变量取代,受jsp等影响。

    过滤器(文档说是 Expression Escaping-表达式转义)

    在变量取代中 | 来表示过滤,内建 u-URL escaping, h-HTML escaping, x-XML escaping,以及trim四个过滤器。

    结构控制


    有if/else/elif, while/for, try/except,用%开头,用%end<name>结尾,name为表达式名称,与python一样,需要尾部添加:来表示一个表达式开始,但缩进不是必须的。

    由于%被特殊使用,所有想要表达%,得用%%

    注释

    和其他语言一样,有单行和多行注释,单行用##,多行用<%doc></%doc>

    换行过滤器

    \在一行的结尾,表示下一行也是这一行的内容,连接上下两行内容为一行内容。

    here is a line that goes onto \
    another line.

    等价:
    here is a line that goes onto another line.

    Python块

    mako支持python代码块,用<%开始,用%>结束

    this is a template
    <%
        x = db.get_resource('foo')
        y = [z.element for z in x if x.frobnizzle==5]
    %>
    % for elem in y:
        element: ${elem}
    % endfor

     

     上面的一个变形是模块级别的支持,用<%!开始

     

    <%!
        import mylib
        import re
    
        def filter(text):
            return re.sub(r'^@', '', text)
    %>

    注意,此处需要纯的python代码

     


    标签

    类似XML,用%开头,用/结束或者显示的结束标签

    <%include file="foo.txt" />

    <%def name="foo" buffered="True">

      this is a def

    </%def>

    所有的tag有各自的属性,大部分属性支持evaluation,这表示你可以在属性文本中使用${}

    <%include file="/foo/bar/${myfile}.txt" />

    下面为所有tag

    <%page>

      每个模板中仅能使用一个<%page>标签,剩下的会被忽略。

    <%include>

      包含一个文件,然后将文件render出来,include可以包含参数

    <%include file="toolbar.html" args="current_section='members', username='ed" />

    <%def>

          定义一个python函数,可以被其他的模板调用

      <%def name="myfunc(x)">

        this is myfunc, x is ${x}

      </%def>

    <%block>

      类似%def,可以匿名,从Jinja2中的block中引用过来

    <%namespace>

      等价于python的import语句,可以用来render函数以及模板文件源数据,python模块等。

    <%inherit>

      允许模板构成继承链,当构成inherit时,控制首先运行inherit部分模板。

    <%nsname:defname>

      任何用户定义的名字,类似于<%call>的行内调用

    <%call>

      比上面的<%nsname:defname>要复杂

    <%doc>

      多行注释

    <%text>

      挂起mako语法分析,返回整个文本,通常用来编写文档时使用

    从模板中快速返回

        有时候想要停止处理模板或者<%def>,在python的block中使用return语句。

    %if not len(records):

         no records found.

      <% return %>

    %endif

    <%

      if not len(records):

        return

    %>

     

     

  • 相关阅读:
    APP-5-百度电子围栏
    APP-4-百度地图定位
    洗礼灵魂,修炼python(60)--爬虫篇—httplib2模块
    洗礼灵魂,修炼python(59)--爬虫篇—httplib模块
    洗礼灵魂,修炼python(58)--爬虫篇—【转载】urllib3模块
    洗礼灵魂,修炼python(57)--爬虫篇—知识补充—编码之对比不同python版本获取的数据
    洗礼灵魂,修炼python(56)--爬虫篇—知识补充—编码之url编码
    洗礼灵魂,修炼python(55)--爬虫篇—知识补充—RFC 2616 http状态码
    洗礼灵魂,修炼python(54)--爬虫篇—urllib2模块
    洗礼灵魂,修炼python(53)--爬虫篇—urllib模块
  • 原文地址:https://www.cnblogs.com/ubunoon/p/2611524.html
Copyright © 2011-2022 走看看