在 django 中使用 mako or jinja2 (精简版) - Python,Django - language - ITeye论坛
介绍:mako模版跟据多方测试,是目前渲染最快的模版。好不好用,仁者见仁。
下面是我从网上总结下来的精简版。jinja2 也可以用,只要小改一下。
- #mymako.pyfrom django.template.context import Context
- from django.http import HttpResponse
- from mako.template import Template
- from mako.lookup import TemplateLookup
- import os
- def render_to_response(t,c=None,context_instance=None):
- path = os.path.join(os.path.dirname(__file__), 'templates/')
- mylookup = TemplateLookup(directories=[path],output_encoding='utf-8',input_encoding='utf-8')
- mako_temp = mylookup.get_template(t)
- if context_instance:
- context_instance.update(c)
- else:
- context_instance = Context(c)
- data = {}
- for d in context_instance:data.update(d)
- return HttpResponse(mako_temp.render(**data))
#mymako.pyfrom django.template.context import Context from django.http import HttpResponse from mako.template import Template from mako.lookup import TemplateLookup import os def render_to_response(t,c=None,context_instance=None): path = os.path.join(os.path.dirname(__file__), 'templates/') mylookup = TemplateLookup(directories=[path],output_encoding='utf-8',input_encoding='utf-8') mako_temp = mylookup.get_template(t) if context_instance: context_instance.update(c) else: context_instance = Context(c) data = {} for d in context_instance:data.update(d) return HttpResponse(mako_temp.render(**data))
把上面这个 mymako.py 放到 project下,随时就可以调用了,下面是调的例子:
- #views.py
- from django.template import RequestContext
- from mymako import render_to_response
- from django import forms
- def index(request):
- if request.method == 'GET':
- form = MyForm()
- else:
- form = MyForm(request.POST)
- return render_to_response('mako_temp.html',{'form':form},RequestContext(request))
- class MyForm(forms.Form):
- name = forms.CharField(label='name',required=True)
#views.py from django.template import RequestContext from mymako import render_to_response from django import forms def index(request): if request.method == 'GET': form = MyForm() else: form = MyForm(request.POST) return render_to_response('mako_temp.html',{'form':form},RequestContext(request)) class MyForm(forms.Form): name = forms.CharField(label='name',required=True)
mako_temp.html
- <html>
- <head>
- </head>
- <body>
- <form action="." method="post">
- ${form}<br />
- <input type="submit" value="post"/>
- </form>
- </body>
- </html>