tornado模板机制_在模板里面编程

来源:互联网 发布:淘宝怎么导出客户资料 编辑:程序博客网 时间:2024/06/06 06:40

模板的名字空间

tornado的模板机制是出了名的灵活.

我以前的一篇博客已经讲过了,原因是因为,tornado渲染生成模板对象的时候,是把html文件一句句的读入python中,然后按照python的语句来解析执行.所以,tornado里面几乎可以使用所有的python语句来进行编程.

而且在模板中,有一个名字空间, 我们可以去get_template_namespace这个方法去查看, 所以在模板中,我们可以任意使用一些预定义好的变量.

def get_template_namespace(self):        """Returns a dictionary to be used as the default template namespace.        May be overridden by subclasses to add or modify values.        The results of this method will be combined with additional        defaults in the `tornado.template` module and keyword arguments        to `render` or `render_string`.        """        namespace = dict(            handler=self,            request=self.request,            current_user=self.current_user,            locale=self.locale,            _=self.locale.translate,            static_url=self.static_url,            xsrf_form_html=self.xsrf_form_html,            reverse_url=self.reverse_url        )        namespace.update(self.ui)        return namespace
当然,我们也可以重载这个方法,然后加入,修改一些新的变量,这些变量在模板里是全局可用的.

模板里传参数并表达成html的表达式

有时候,我们需要传入参数,然后定制一些html标签,该怎么办?

有一个思路:

(1)实现一个ui module组件.

(2)在这个组件中渲染一个字符串表达式. 比如 "class="bababa""

这样我们就可以将这个字符串转化成html的表达式了.

python是强类型语言.

我们可以在模板中使用{{str(a)}}, python的任何内置变量都是可以在模板中使用的.
{{"1"+1}}这样会出错,因为我们的python是强类型语言,不会进行隐式的,含糊的转换.不同类型之间不能进行操作.

小注:
{%set buttion=1%}  正确
{%set buttion={
1:1}
%}   正确

{%set

 buttion=1%}  错误


这样在ui模板中渲染的时候{{"..."}}, 就不是表达式了,

比如: 如果a="fa fa"

在ui 渲染 key  = {{a}}的时候, 结果是 key = "fa" fa 

正确应该是: key = "{{a}}"  , 结果: key = "fa fa"

0 0
原创粉丝点击