zoukankan      html  css  js  c++  java
  • 在 django 中使用 mako or jinja2 (精简版) Python,Django language ITeye论坛

    在 django 中使用 mako or jinja2 (精简版) - Python,Django - language - ITeye论坛

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

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


    Python代码  收藏代码
    1. #mymako.pyfrom django.template.context import Context  
    2. from django.http import HttpResponse  
    3. from mako.template import Template  
    4. from mako.lookup import TemplateLookup  
    5. import os  
    6.   
    7. def render_to_response(t,c=None,context_instance=None):  
    8.     path = os.path.join(os.path.dirname(__file__), 'templates/')  
    9.     mylookup = TemplateLookup(directories=[path],output_encoding='utf-8',input_encoding='utf-8')  
    10.     mako_temp = mylookup.get_template(t)  
    11.     if context_instance:  
    12.         context_instance.update(c)  
    13.     else:  
    14.         context_instance = Context(c)  
    15.     data = {}  
    16.     for d in context_instance:data.update(d)  
    17.     return HttpResponse(mako_temp.render(**data))  


    把上面这个 mymako.py 放到 project下,随时就可以调用了,下面是调的例子:


    Python代码  收藏代码
    1. #views.py  
    2. from django.template import RequestContext  
    3. from mymako import render_to_response  
    4. from django import forms  
    5.   
    6. def index(request):  
    7.     if request.method == 'GET':  
    8.         form = MyForm()  
    9.     else:  
    10.         form = MyForm(request.POST)  
    11.     return render_to_response('mako_temp.html',{'form':form},RequestContext(request))  
    12.   
    13. class MyForm(forms.Form):  
    14.     name = forms.CharField(label='name',required=True)  




    mako_temp.html


    Html代码  收藏代码
    1. <html>  
    2. <head>  
    3. </head>  
    4. <body>  
    5. <form action="." method="post">  
    6. ${form}<br />  
    7. <input type="submit" value="post"/>  
    8. </form>  
    9. </body>  
    10. </html>  
  • 相关阅读:
    Mysql登录错误:ERROR 1045 (28000): Plugin caching_sha2_password could not be loaded
    Docker配置LNMP环境
    Docker安装mysqli扩展和gd扩展
    Docker常用命令
    Ubuntu常用命令
    单例模式的优缺点和使用场景
    ABP 多租户数据共享
    ABP Core 后台Angular+Ng-Zorro 图片上传
    ERROR Error: If ngModel is used within a form tag, either the name attribute must be set or the form control must be defined as 'standalone' in ngModelOptions.
    AbpCore 执行迁移文件生成数据库报错 Could not find root folder of the web project!
  • 原文地址:https://www.cnblogs.com/lexus/p/2475156.html
Copyright © 2011-2022 走看看