簡単な体験python mako

4260 ワード

djangoが持参したテンプレートは不快に使い、python Makoに置き換える準備をしています.これも豆弁で使われているテンプレート言語です.
1.環境準備
pipを直接使うと、pipとは何か分からないと、死ぬのが惨めです.
sudo pip install Mako
sudo pip install django-mako
2.簡単な例

from mako.template import Template

mytemplate = Template("hello world!")
print mytemplate.render()

Javaのテンプレートシステムと大同小異、contextを加える:
from mako.template import Template

mytemplate = Template("hello, ${name}!")
print mytemplate.render(name="jack")

ここでrenderメソッドはContextオブジェクトを自動的に作成するか、Contextを自分で作成することができます.

from mako.template import Template
from mako.runtime import Context
from StringIO import StringIO

mytemplate = Template("hello, ${name}!")
buf = StringIO()
ctx = Context(buf, name="jack")
mytemplate.render_context(ctx)
print buf.getvalue()

3.ファイルベースのTemplates
上記の例では、Templateは文字列によって構築されています.次に、ファイルについて説明します.
from mako.template import Template

mytemplate = Template(filename='/docs/mytmpl.txt')
print mytemplate.render()

4.文法
a.式、jsp、velocityに似ています.
this is x: ${x}

しかしvelocityよりもスマートで、数学の演算は便利です.
${pow(x,2) + pow(y,2)}
the contents within the ${} tag are evaluated by Python directly, so full expressions are OK.
Javaよりも先進的なものもあります
${"this is some text" | u}

后ろのこれはどういう意味ですか.
Makoには、HTML、URL、XML escaping、trim()など、複数のescaping filterが内蔵されており、これらのfilterは|後に式で表すことができます.
    u : URL escaping, provided by urllib.quote_plus(string.encode('utf-8'))
    h : HTML escaping, provided by markupsafe.escape(string)
    x : XML escaping
    trim : whitespace trimming, provided by string.strip()
    entity : produces HTML entity references for applicable strings, derived from htmlentitydefs
    unicode (str on Python 3): produces a Python unicode string (this function is applied by default)
    decode. : decode input into a Python unicode with the specified encoding
    n : disable all default filtering; only filters specified in the local expression tag will be applied.
複数のフィルタはカンマで間隔を置きます.
${" <tag>some value</tag> " | h,trim}

上のcodeは,<tag>some value</tag> 詳細:http://docs.makotemplates.org/en/latest/filtering.html
b.プロセス制御


% if x==5:
    this is some output
% endif

% for a in ['one', 'two', 'three', 'four', 'five']:
    % if a[0] == 't':
    its two or three
    % elif a[0] == 'f':
    four/five
    % else:
    one
    % endif
% endfor


c. python block:

this is a template
<%
    x = db.get_resource('foo')
    y = [z.element for z in x if x.frobnizzle==5]
%>
% for elem in y:
    element: ${elem}
% endfor

詳細:http://docs.makotemplates.org/en/latest/syntax.html
5.最後にdjangoとの統合について述べる
1)djangoプロジェクトのsettings.pyのMIDDLEWARE_CLASSESにdjangomako.middleware.MakoMiddlewareの例を追加します.

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'djangomako.middleware.MakoMiddleware',
    )

djangoメソッドを追加します.例:

from djangomako.shortcuts import render_to_response
def hello_view(request):
    return render_to_response('hello.html', {'name':'sand'})

djangoプロジェクトを起動して、ブラウザにアクセスしてください.http://yourhostname/helloああ、戻ってきたhello sandを見たかどうか見てみましょう!
http://www.sandzhang.com/blog/2010/04/03/install-mako-templates-and-plugin-for-django/