zoukankan      html  css  js  c++  java
  • mako表达式过滤器(五)

    默认支持的有

    u - URL

    h - HTML

    x - XML

    trim - string.strip()

    entity - HTML entity

    unicode - 默认的unicode字符串

    decode

    n - 取消所有的默认filter

    多个filter时,用comma(,)隔开,也可以自己定义filter

    <%!
         def myescape(text):
             return "<TAG>" + text + "</TAG>"
    %>

    Here's some tagged text : ${"text" | myescape }

    自己定义的filter需要为支持一个字符串的参数并且返回过滤后结果。

    在<%page>标签中使用expression_filter可以为整个页面使用该过滤器。

    也可以为block和def设置filter

    <%def name="foo()" filter="h, trim">
        <b>this is bold</b>
    </%def>

    在执行

    ${" results " + somedef() + " more results "}

    时会返回(假定somedef返回“somedef's results”字符串)

    somedef's results results more results

    这是由于somedef()在字符串链接前被全部执行,链接字符串将得到一个空的字符串返回值,为避免该问题,mako有两种方法:

    <%def name="somedef()" buffered="True">
        somedef's results
    </%def>

    上面的代码会生成类似下面的代码:

    def somedef():
        context.push_buffer()
        try:
            context.write("somedef's results")
        finally:
            buf = context.pop_buffer()
        return buf.getvalue()

    或者使用

    ${" results " + capture(somedef) + " more results "}

    capture类似python的apply方法,传递给somedef的参数,可由capture传递给somedef。

    在使得def更加灵活对待filter,decorator在template中也支持。

    <%!
        def bar(fn):
            def decorate(context, *args, **kw):
                context.write("BAR")
                fn(*args, **kw)
                context.write("BAR")
                return ''
            return decorate
    %>
    
    <%def name="foo()" decorator="bar">
        this is foo
    </%def>
    
    ${foo()}
    /*
    *
    * Copyright (c) 2011 Ubunoon.
    * All rights reserved.
    *
    * email: netubu#gmail.com replace '#' to '@'
    * http://www.cnblogs.com/ubunoon
    * 欢迎来邮件定制各类验证码识别,条码识别,图像处理等软件
    * 推荐不错的珍珠饰品,欢迎订购 * 宜臣珍珠(淡水好珍珠) */
  • 相关阅读:
    AsyncHttpClient使用
    索引
    jdbc--取大量数据
    oracle--with as
    spring--mybatis事务总结
    Elasticsearch环境搭建
    使用idea远程调试
    redis分布式锁的实现
    知识梳理
    Zookeeper
  • 原文地址:https://www.cnblogs.com/ubunoon/p/2612150.html
Copyright © 2011-2022 走看看