介绍:mako模版跟据多方测试,是目前渲染最快的模版。好不好用,仁者见仁。

下面是我从网上总结下来的精简版。jinja2 也可以用,只要小改一下。

Python代码
  1. #mymako.pyfromdjango.template.contextimportContext
  2. fromdjango.httpimportHttpResponse
  3. frommako.templateimportTemplate
  4. frommako.lookupimportTemplateLookup
  5. importos
  6. defrender_to_response(t,c=None,context_instance=None):
  7. path=os.path.join(os.path.dirname(__file__),'templates/')
  8. mylookup=TemplateLookup(directories=[path],output_encoding='utf-8',input_encoding='utf-8')
  9. mako_temp=mylookup.get_template(t)
  10. ifcontext_instance:
  11. context_instance.update(c)
  12. else:
  13. context_instance=Context(c)
  14. data={}
  15. fordincontext_instance:data.update(d)
  16. 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下,随时就可以调用了,下面是调的例子:

Python代码
  1. #views.py
  2. fromdjango.templateimportRequestContext
  3. frommymakoimportrender_to_response
  4. fromdjangoimportforms
  5. defindex(request):
  6. ifrequest.method=='GET':
  7. form=MyForm()
  8. else:
  9. form=MyForm(request.POST)
  10. returnrender_to_response('mako_temp.html',{'form':form},RequestContext(request))
  11. classMyForm(forms.Form):
  12. 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代码
  1. <html>
  2. <head>
  3. </head>
  4. <body>
  5. <formaction="."method="post">
  6. ${form}<br/>
  7. <inputtype="submit"value="post"/>
  8. </form>
  9. </body>
  10. </html>

发表回复