运维的我要学开发--Flask(1)
时间:2014-05-11 19:25:12
收藏:0
阅读:443
Flask默认使用的是Jinja2的模板引擎,下面将会介绍下Flask提供给模板的一些方法。
#-*- coding: utf-8 -*-
#导入一些函数
from flask import Flask
from flask import render_template,g
#创建一个app
app = Flask(__name__)
#创建一个装饰器
@app.route("/")
@app.route("/index")
def index():
string="<h1>11</h1>"
g.test = "I am a g variable"
#默认会转义html标签,如果不想转义可以通过|safe来关闭转义
#或者通过下面模板标签来关闭html标签转义
#{% autoescape false %}
#{% endautoescape %}
return render_template("test.html",name=g.test)
#测试g.test是不是可以全局
#测试结果表明g.test是不可以夸request的
@app.route("/test")
def test():
return render_template("test.html",name=g.test)
#创建全局的模板变量或函数
#下面创建的test变量可以在所有的模板中使用
@app.context_processor
def inject_user():
return dict(test="<h1>a tmp variable</h1>")
#下面的functest函数也是可以在所有的模板中使用的
@app.context_processor
def testfunc():
def functest(name):
return "<h1>%s</h1>" %name
return dict(functest=functest)
#注册一个过滤器
#方式一
##@app.template_filter(‘reverse‘)
##def reverse_filter(s):
###方式二
def reverse_filter(s):
return s[::-1]
app.jinja_env.filters[‘reverse‘] = reverse_filter
#运行app
if __name__ == "__main__":
app.run(debug=True,host=‘0.0.0.0‘)下面是templates目录的下test,html模板
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>测试页面</title>
</head>
<body>
<h1>转义后的页面</h1>
{{ name|safe }}
<h1>没有转义后的页面</h1>
{{ name }}
<h1>下面这块区域自动转义关闭了</h1>
{% autoescape false %}
<p>autoescaping is disabled here
<p>{{ name }}
{% endautoescape %}
{{ name|reverse }}
<h1>我是test变量 通过context_processor传递过来的</h1>
{{ test }}
<h1>我是通过context_processor注册的函数</h1>
{{ functest("你好") }}
</body>
</html>运行后结果如下:
下面是放我http://127.0.0.1:5000/test页面的结果,因为g.user只是在一个request中共享,所以这个变量是不存在的所以报错。
本文出自 “专注linux” 博客,请务必保留此出处http://forlinux.blog.51cto.com/8001278/1409354
评论(0)

