使用 TurboGears 和 Python 开发 Web 站点

豆豆网   技术应用频道   2007年03月30日    社区交流

本文详细介绍使用 TurboGears 和 Python 开发 Web 站点

  清单 11 展示了一些关键的 Kid 功能:

  使用 py:extends 继承 master.kid

  在 title 中使用 ${category.name} 进行表达式替换

  使用 py:for 遍历祖先、子分类和产品

  使用限制逻辑对在 breadcrumb 中显示的祖先进行反向

  使用 py:content 填充链接文本

  使用 py:replace 完全替换 span 标记

  上面引用的 ancestors 属性要想有效,Category 模型类需要修改成包含一个 _get_ancestors 方法:

  清单 12. 将 “ancestors” 属性的 “get” 方法添加到 Category 类中

class Category(SQLObject):
  name = StringCol(length=64)
  parent = ForeignKey('Category', default=None)
  subcategories = MultipleJoin('Category', joinColumn='parent_id')
  products = MultipleJoin('Product')
  def _get_ancestors(self):
  ancestor = self.parent
  while ancestor:
    yield ancestor
    ancestor = ancestor.parent

  创建控制器

  TurboGears quickstart 提供了一个具有 controllers.py 模块的项目,该模块是 Root 控制器类所在的位置。这是应用程序的主入口点,也是添加新控制器方法的地方。

  下面是 TurboGears expose 中与分类 HTML 模板有关的两个样例控制器方法。控制器方法会返回字典,它们在对指定的 Kid 模板进行呈现时被用作名称空间或上下文。

  清单 13. 控制器类

from turbogears import controllers, expose
class Root(controllers.Root):
  @expose("tgcommerce.templates.category")
  def index(self):
  from model import Category
  category = Category.selectBy(parent=None)[0]
  return dict(category=category)
  @expose("tgcommerce.templates.category")
  def category(self, categoryID):
  from model import Category
  category = Category.get(categoryID)
  return dict(category=category)

责编:豆豆技术应用

正在加载评论...