App Engine中文教程

使用模板|中文版Google App Engine入门指南

HTML里面嵌入在编程代码里是非常杂乱的,所以我们最好使用一个独立的文件来专门处理HTML代码,以便于将界面显示和数据获取的过程相互独立出来。有很多使用Python实现的模板系统,比如: EZTCheetah,ClearSilverQuixote,  Django 等等.你可以选择这里面的任意一个。

为了大家方便,  webapp 模块默认包含了Django的模板系统.Django模板是Google App Engine的一部分,所以你不需要单独进行绑定就可以直接使用。

使用 Django 模板

首先在 helloworld/helloworld.py中引入template模块:

import os
from google.appengine.ext.webapp import template

重新编写 MainPage handler:

class MainPage(webapp.RequestHandler):
 
def get(self):
    greetings_query
= Greeting.all().order('-date')
    greetings
= greetings_query.fetch(10)

   
if users.get_current_user():
      url
= users.create_logout_url(self.request.uri)
      url_linktext
= 'Logout'
   
else:
      url
= users.create_login_url(self.request.uri)
      url_linktext
= 'Login'

    template_values
= {
     
'greetings': greetings,
     
'url': url,
     
'url_linktext': url_linktext,
     
}

    path
= os.path.join(os.path.dirname(__file__), 'index.html')
    self
.response.out.write(template.render(path, template_values))

最后, 在 helloworld 的目录下面创建一个新文件index.html, 内容如下:

<html>
  <body>
    {% for greeting in greetings %}
      {% if greeting.author %}
        <b>{{ greeting.author.nickname }}</b> wrote:
      {% else %}
       An anonymous person wrote:
      {% endif %}
      <blockquote>{{ greeting.content|escape }}</blockquote>
    {% endfor %}

    <form action="/sign" method="post">
      <div><textarea name="content" rows="3" cols="60"></textarea></div>
      <div><input type="submit" value="Sign Guestbook"></div>
    </form>

    <a href="{{ url }}">{{ url_linktext }}</a>

  </body>
</html>

刷新浏览器,然后查看网页上的变化。

template.render(path, template_values) 接受输入一个文件路径和一个dictionary类型的数据字典,并输出一段经过处理的文本。这个模板使用了Django模板的语法.在模板文件中可以直接使用引入的值,并且可以使用这些对象的属性。在许多实际例子里,你可以直接使用GAE数据模型,并访问他们的属性。

提示: App Engine 应用程序对所有上传的文件的访问权限都是只读的,所以对文件的写操作是被禁止的;当前工作路径是应用程序的根目录,所以 index.html 的路径可以简单写成"index.html"

想要了解更多关于Django模板引擎的内容,参见 the Django 0.96 template documentation


上一页 下一页

如果大家对于教程里的内容有疑问,或是想要参加到教程的编写工作中,欢迎访问:

康爷的博客