介绍:mako模版跟据多方测试,是目前渲染最快的模版。好不好用,仁者见仁。
下面是我从网上总结下来的精简版。jinja2 也可以用,只要小改一下。
- #mymako.pyfromdjango.template.contextimportContext
- fromdjango.httpimportHttpResponse
- frommako.templateimportTemplate
- frommako.lookupimportTemplateLookup
- importos
- defrender_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)
- ifcontext_instance:
- context_instance.update(c)
- else:
- context_instance=Context(c)
- data={}
- fordincontext_instance:data.update(d)
- returnHttpResponse(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
- fromdjango.templateimportRequestContext
- frommymakoimportrender_to_response
- fromdjangoimportforms
- defindex(request):
- ifrequest.method=='GET':
- form=MyForm()
- else:
- form=MyForm(request.POST)
- returnrender_to_response('mako_temp.html',{'form':form},RequestContext(request))
- classMyForm(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>
- <formaction="."method="post">
- ${form}<br/>
- <inputtype="submit"value="post"/>
- </form>
- </body>
- </html>