pyramid web framework [note pieces] 模板引擎

pyramid.

The default templates engine of Pyramid web framework is chameleno which is frustrating to read and write.



And another guy in #pyramid called sontek suggested me to use mako http://www.makotemplates.org/ that it's syntax is easy and clear.

Mako Templates for Python

Mako is a template library written in Python. It provides a familiar, non-XML syntax which compiles into Python modules for maximum performance. Mako's syntax and API borrows from the best ideas of many others, including Django and Jinja2 templates, Cheetah, Myghty, and Genshi. Conceptually, Mako is an embedded Python (i.e. Python Server Page) language, which refines the familiar ideas of componentized layout and inheritance to produce one of the most straightforward and flexible models available, while also maintaining close ties to Python calling and scoping semantics.

Mako is used by the python.org website, as well as reddit.com where it delivers over one billion page views per month. It is the default template language included with the Pylons and Pyramid web frameworks.

Nutshell:

<%inherit file="base.html"/>
<%
    rows = [[v for v in range(0,10)] for row in range(0,10)]
%>
<table>
    % for row in rows:
        ${makerow(row)}
    % endfor
</table>

<%def name="makerow(row)">
    <tr>
    % for name in row:
        <td>${name}</td>\
    % endfor
    </tr>
</%def>

Philosophy:

Python is a great scripting language. Don't reinvent the wheel...your templates can handle it !

Features:

  • Super-simple API. For basic usage, just one class, Template is needed:
    from mako.template import Template
    print Template("hello ${data}!").render(data="world")
    
    For filesystem management and template caching, add the TemplateLookup class.
  • Super fast. As templates are ultimately compiled into Python bytecode, Mako's approach is extremely efficient, and was originally written to be just as fast as Cheetah. Today, Mako is very close in speed to Jinja2, which uses a similar approach and for which Mako was an inspiration.
  • Standard template features
    • control structures constructed from real Python code (i.e. loops, conditionals)
    • straight Python blocks, inline or at the module-level
    • plain old includes
  • Callable blocks
    • two types - the <%def> tag provides Python def semantics, whereas the <%block> tag behaves more like a Jinja2 content block.
    • can access variables from their enclosing scope as well as the template's request context
    • can be nested arbitrarily
    • can specify regular Python argument signatures
    • outer-level callable blocks can be called by other templates or controller code (i.e. "method call")
    • Calls to functions can define any number of sub-blocks of content which are accessible to the called function This is the basis for nestable custom tags.
  • Inheritance
    • supports "multi-zoned" inheritance - define any number of areas in the base template to be overridden using <%block> or<%def>.
    • supports "chaining" style inheritance - call next.body() to call the "inner" content.
    • the full inheritance hierarchy is navigable in both directions (i.e. parent and child) from anywhere in the chain.
    • inheritance is dynamic! Specify a function instead of a filename to calculate inheritance on the fly for every request.
  • Full-Featured
    • filters, such as URL escaping, HTML escaping. Markupsafe is used for performant and secure HTML escaping, and new filters can be constructed as a plain Python callable.
    • complete caching system, allowing caching to be applied at the page level or individual block/def level. The caching system includes an open API that communicates with Beaker and soon dogpile.cache by default, and new cache backends can be added with ease via setuptools entrypoints.
    • Supports Python 2.4 through modern 3 versions.
    • Supports Google App Engine.

To get started, visit the documentation and the download page.

Mako is covered by the MIT License.


Here is something about chameleno 

http://chameleon.repoze.org/docs/latest/

Introduction

The page templates language is used within your document structure as special element attributes and text markup. Using a set of simple language constructs, you control the document flow, element repetition, text replacement and translation.

Note

 

If you’ve used page templates in a Zope environment previously, note that Chameleon uses Python as the default expression language (instead of path expressions).

The basic language (known as the template attribute language or TAL) is simple enough to grasp from an example:

<html>
  <body>
    <h1>Hello, ${'world'}!</h1>
    <table>
      <tr tal:repeat="row 'apple', 'banana', 'pineapple'">
        <td tal:repeat="col 'juice', 'muffin', 'pie'">
           ${row.capitalize()} ${col}
        </td>
      </tr>
    </table>
  </body>
</html>

The ${...} notation is short-hand for text insertion [3]. The Python-expression inside the braces is evaluated and the result included in the output. By default, the string is escaped before insertion. To avoid this, use the structure: prefix:

<div>${structure: ...}</div>

Note that if the expression result is an object that implements an __html__() method [4], this method will be called and the result treated as “structure”. An example of such an object is the Markup class that’s included as a utility:

from chameleon.utils import Markup
username = "<tt>%s</tt>" % username

The macro language (known as the macro expansion language or METAL) provides a means of filling in portions of a generic template.

On the left, the macro template; on the right, a template that loads and uses the macro, filling in the “content” slot:

<html xmlns="http://www.w3.org/1999/xhtml">             <metal:main use-macro="load: main.pt">
  <head>                                                   <p metal:fill-slot="content">${structure: document.body}<p/>
    <title>Example &mdash; ${document.title}</title>    </metal:main>
  </head>
  <body>
    <h1>${document.title}</h1>

    <div id="content">
      <metal:content define-slot="content" />
    </div>
  </body>
</html>

In the example, the expression type load is used to retrieve a template from the file system using a path relative to the calling template.

The METAL system works with TAL such that you can for instance fill in a slot that appears in atal:repeat loop, or refer to variables defined using tal:define.

The third language subset is the translation system (known as the internationalization language or I18N):

<html i18n:domain="example">

  ...

  <div i18n:translate="">
     You have <span i18n:name="amount">${round(amount, 2)}</span> dollars in your account.
  </div>

  ...

</html>

Each translation message is marked up using i18n:translate and values can be mapped using i18n:name. Attributes are marked for translation using i18n:attributes. The template engine generates gettexttranslation strings from the markup:

"You have ${amount} dollars in your account."

If you use a web framework such as Pyramid, the translation system is set up automatically and will negotiate on a target language based on the HTTP request or other parameter. If not, then you need to configure this manually.


I don't prefer chameleno. I'd like the mako one.

Syntax really does matter! :D


这个叫sontek的人的博客

http://sontek.net/blog/category/tech 就是用pyramid 完成的,里面有不少好东西。他两年前用django, 现在完全用pyramid. 对pyramid期待很大,说未来到处都是pyramid.

这里还有他最近完成的项目:http://eventray.com

Turning Vim into a modern Python IDE

http://sontek.net/blog/detail/turning-vim-into-a-modern-python-ide 





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值