模板的基本使用
Bottle內置了一個快速強大的模板引擎,稱爲SimpleTemplate模板引擎。可通過template() 函
數或view()修飾器來渲染一個模板。只需提供模板的名字和傳遞給模板的變量。如下:
[root@jubottle]# tree .
.
├── templ.py
└── views
└── hello.tpl
1directories, 2files
[root@jubottle]# cat templ.py #!/usr/bin/envpython #coding=utf-8 frombottle import route,run,template @route('/hello') defhello(): return template('hello') run(host='0.0.0.0',port=8000,debug=True)
[root@jubottle]# cat views/hello.tpl <html> <head> <title>hello page!</title> </head> <body> <h1>hello world!</h1> <h2>hello world!</h2> <h3>hello world!</h3> </body> </html>
在瀏覽器中輸入:http://192.168.116.199:8000/hello
默認情況,Bottle會在./views/目錄查找模板文件(或當前目錄)。也可以使用bottle.TEMPLATE_PATH.append('目錄地址')的方式來增加更多的模板路徑。
給模板傳遞數據
[root@jubottle]# cat templ.py #!/usr/bin/envpython #coding=utf-8 frombottle import route,run,template @route('/hello') defhello(): name="乾楠有" age="29" weight="138" blog="http://changfei.blog.51cto.com" returntemplate('hello_template',name=name,age=age,weight=weight,blog=blog) run(host='0.0.0.0',port=8000,debug=True)
[root@jubottle]# cat views/hello_template.tpl <html> <head> <title>my infomatiom!</title> </head> <body> <h1>My infomation</h1> <p>姓名:{{ name }}</p> <p>年齡:{{ age }}</p> <p>體重:{{ weight}}</p> <p>博客:{{ blog }}</p> </body> </html>
在瀏覽器中輸入:http://192.168.116.199:8000/hello
使用view()修飾器來渲染模版
view()修飾器允許你在回調函數中返回一個字典,並將其傳遞給模板,和template()函數做同樣的事情。
[root@ju bottle]# cat templ.py #!/usr/bin/env python #coding=utf-8 from bottle import route,run,view #導入view模塊 @route('/hello') @view('hello_template') #使用view()修飾器來渲染模版 def hello(): name="乾楠有" age="29" weight="138" blog="http://changfei.blog.51cto.com" info={'name':name,'age':age,'weight':weight,'blog':blog} #這裏使用字典傳送數據到模版 return info run(host='0.0.0.0',port=8000,debug=True)
在瀏覽器中輸入:http://192.168.116.199:8000/hello
在模版中顯示一個列表或字典傳過來的值
[root@ju bottle]#cat templ.py #!/usr/bin/envpython #coding=utf-8 from bottle importroute,run,view #導入view @route('/hello') @view('hello_template')#使用view()修飾器來渲染模版 def hello(): name="乾楠有" blog="http://changfei.blog.51cto.com" myfriend=['奧巴馬','普京','卡梅倫'] myinfodir={'age':29,'weight':138} info={'name':name,'age':myinfodir,'weight':myinfodir,'blog':blog,'SNS':myfriend}#這裏使用字典傳送數據到模版 return info run(host='0.0.0.0',port=8000,debug=True)
[root@ju bottle]#cat views/hello_template.tpl <html> <head> <title>my infomatiom!</title> </head> <body> <h1>My infomation</h1> <p>姓名:{{ name}}</p> <p>年齡:{{age.get('age') }}</p> #使用字典的get方法獲取值 <p>體重:{{weight.get('weight')}}</p> <p>博客:{{ blog}}</p> <p>朋友圈: %for i in SNS: #遍歷SNS這個列表 {{ i }} %end </p> </body> </html>
在瀏覽器中輸入:http://192.168.116.199:8000/hello