flask html模版文件的放置和 访问 ,视图函数访问html模版和传参

一、模版的放置位置

常规情况下是在app的根目前 创建 templates文件夹,然后放入html文件

使用url访问 http://0.0.0.0:5000/templates/lucax.html 就可以访问成功

 

和访问静态文件一样,也有 设置静态文件路径、和 访问静态文件url的参数设置

app = Flask(__name__,template_folder="/lucax",template_url_path='/uuu')

 

当需要把 templates文件夹移入蓝图下,也只要修改蓝图的 参数(注意相对路径,蓝图的根目前和应该的有区别)

web=Blueprint("web",__name__,template_folder="/lucax",template_url_path='/uuu')

 

二、视图函数访问模版 使用 render_template函数

@web.route("/test")

def test():
  r={

  'name':"lucax",

  'age':18
  }
  r2=[ 
1 ,  15 ]  

#模版使用
return render_template('test.html',data=r,data2=r2)       # render_template('要使用的模版文件,data=要传入的参数1,data2=要传入的参数2)参数可以传多个,其中data和data1 可以随意命名 不要总重复即可,还可以render_template('test.html',data=r,data2=r2)  ,200 指定响应代码

 

test.html 模版内引用参数变量的方法,获取变量是 2个花括号{{ }}

这里使用的是jianja2的语法去渲染,见jianjia2官网 or

参考下 

https://www.jianshu.com/p/83f5c3fd264c

https://www.cnblogs.com/kaibindirver/p/12869496.html

<body>
刘大兵 年龄 {{data2[0]}}   #访问数组
</br>
刘大兵 年龄 {{data.age}}  #访问字典
</body>

posted @ 2020-05-11 12:54  凯宾斯基  阅读(975)  评论(0编辑  收藏  举报