Template Language Plugins
PyLons 通过使用模板引擎插件可以支持除 Myghty 以外的许多模板语言. 如果你是要将 web应用程序 移植到 PyLons , 或者你就是喜欢另一种模板方案, 这都是很有用的.
使用 setuptools 可以很容易地安装模板语言插件. 目前模板引擎插件列表在站点 Buffet 上.
一旦你安装了其中之一, 那么在 PyLons 中使用新的模板语言就很容易了. 因为 PyLons 设计之初就没有考虑要绑定特定的模板语言, 你只需要另外再做一小点工作就可以了, 具体工作量取决于你要使用的模板语言.
示例: 在 PyLons 中使用 Kid
要在 PyLons 中使用 Kid, 首先我们必须为 Kid 模板设置一个新的模板目录.
首先, 在 yourproject 中建一个叫 kidtemplates 的目录并添加一个 controller:
~/yourproject% mkdir yourproject/kidtemplates ~/yourproject% paster controller kid
现在在你的 controllers 目录下就有了一个 kid.py 文件. 首先, 我们需要将 Kid 添加到可用的模板引擎列表.
编辑 yourproject/config/middleware.py, 就在 config.init_app.... 的后面写上 :
编辑 KidController 类, 让它像这样:
Make sure to change yourproject.kidtemplates to reflect what your project is actually called. The first argument to render or render_response can be the template engine to use, while the second non-keyword argument is the template. If you don't specify a template engine, it will drop back to the default (Myghty, unless you change the default).
现在让我们来添加一个 Kid 模板, 创建文件 yourproject/kidtemplates/test.kid , 内容如下:
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:py="http://purl.org/kid/ns#"> <head> <title py:content="c.title">title</title> </head> <body> <p py:content="c.message">message</p> <p>You made it to the following url: ${h.url_for()}</p> </body> </html>
既然模板插件把路径当模块导入, 你还需要在 yourproject/kidtemplates 里创建一个 __init__.py 文件.
现在加载 /kid 应该会返回你刚创建的那个 Kid 模板.
注意传给模板插件的 PyLons 变量都是一样的. 任何你选择的模板语言中都可用以下变量: c, h, g, session, 和 request. 这也使得不用修改 controller action 就可以容易地切换回 Myghty 或另一种模板语言.
切换默认模板引擎
在 PyLons 中, 我们不仅仅是允许定制, 而是积极地鼓励定制. 将默认模板引擎从 Myghty 修改为其他也是很简单地. 让我们来把 Kid 当做是默认模板引擎吧.
修改 yourproject/config/middleware.py, 在 config.init_app....后面 :
这段代码交换了模板引擎地顺序, 让 Myghty 排在 Kid 地后面, 使得 Kid 成为新地默认模板引擎. 现在前面的 index 方法里渲染一个模板就不再需要指定 'kid' 了.
- 注意:
更多关于 config 对象的细节, 查看 PyLons Module API 中的 可扩展的 config 文档