Google App Engine Template 引擎簡介

教學範例3

所謂的"template"在中文常翻譯成"範本",在Google App Engine上也是相同的概念。當程式執行完成時,會需要將產生的結果呈現在畫面上,此時就需要系統提供一個範本檔,讓程式依照該範本檔案來做輸出。

在範本檔案中會有template引擎的語法來告訴template引擎要在什麼地方填上什麼資料(可能是一個變數、迴圈或判斷等),程式只要利用template引擎將資料餵到範本檔案裡,就可以完成資料畫面的輸出了。

目前Google App Engine預設提供了Django template引擎,所以我們可以使用大部份django template引擎的語法,在使用時,需要先將google.appengine.ext.webapp套件引入。即:

from google.appengine.ext.webapp import template
..........
..........
       content=template.render('index.html',{})
       self.response.out.write(content)


上例是範本檔案中不需要輸出變數,則直接使用render方法帶入範本檔案路徑即可,若程式中需要將變數資料帶入範本中顯示時,則需要多加一個python dict資料結構來傳遞才可,如下所示:

from google.appengine.ext.webapp import template
............
............
      x=1
      y='abc'
      content=template.render('index.html',{'x': x, 'y': y})
      self.response.out.write(content)

template引擎語法

template語法主要區分為三大類:
  • 變數:在範本檔案中使用" {{ "及" }} "所包起來的部份就是直接要輸出的變數名稱。另外,template語法也提供一些用來運算變數資料的過濾器filter,例如" {{strName|lower}} ",就是在輸出變數strName時,使用lower過濾器調整資料後再進行輸出。
  • 標籤Tag:標籤的語法是以" {% "及 " %} "包起來的部份,主要是在做一些控制判斷的輸出動作,例如 " {% for i in list %} .....  {% endfor %}來執行一個迴圈。
  • 註解:用 " {# " 與 " #} "包起來的部份,template引擎會將它當作是程式的註解部份不去執行它所包含的部份。

變數輸出語法

在template引擎中,除了可以直接輸出變數內容外,它也支援複雜的資料結構變數,如dict的資料型態。

py程式:

class TestPage(webapp2.RequestHandler):
    def get(self):
    person={'name':'eric','email':'eric@gmail.com'}
    self.response.out.write(template.render('templates/test.html',{'p':person}))

template程式:

<html>
<head>

</head>
  <body>
    name : {{p.name}}<br />
    email: {{p.email}}<br />
  </body>
</html>

在原本的python程式中,我們要用person['name']及person['email']的方式才能取出dict中的資料,現在在template引擎語法中,我們只要用 " . "運算子即可。

除了dict的資料結構外," . "運算子還可以輸出物件的屬性及方法的回傳結果,如:

python程式:
class Person(object):
    def __init__(self,name,email):
    self.name=name
    self.email=email

    def getNickName(self):
    return 'good guy'

class TestPage(webapp2.RequestHandler):
    def get(self):
    person=Person('eric','eric@gmail.com')
    self.response.out.write(template.render('templates/test.html',{'p':person}))

template程式:
<html>
<head>
</head>
  <body>
    name : {{p.name}}<br />
    email: {{p.email}}<br />
    nick name: {{p.getNickName}}<br />
  </body>
</html>


" . "運算子也可以是list資料結構的index運算
python程式:
class TestPage(webapp2.RequestHandler):
    def get(self):
    person=['eric','eric@gmail.com']
    self.response.out.write(template.render('templates/test.html',{'p':person}))

template程式:
<html>
<head>

</head>
  <body>
    name : {{p.0}}<br />
    email: {{p.1}}<br />

  </body>
</html>

" . "運算子的判斷順序為:

  1. dict資料結構的key。
  2. 物件的屬性。
  3. 物件的方法。
  4. list資料結構的index位置。

變數輸出的過濾器

在template引擎變數輸出的語法中,可以使用 " | " 運算子加在變數後面來調整變數輸出的樣式,部份過濾器可以帶參數來運算。以下列出幾個範例:

  • add  將變數值加上一個設定的數值,如:{{num|add:1000}},最後加總的結果會以整數的資料型態出現。
  • date 將變數的日期進行格式化,如{{now|date:"Y-m-d H:i:s"}}
相關資料可參考

標籤語法

請參考





      

沒有留言: