zoukankan      html  css  js  c++  java
  • 用jinja2替换Django的模板

    整个项目的文件结构如下:

     ~/hg_repo/Django/Django$ tree

    .
    ├── index.py
    ├── __init__.py
    ├── jobs
    │   ├── __init__.py
    │   ├── models.py
    │   ├── templates
    │   │   ├── __init__.py
    │   │   ├── job_base.html
    │   │   └── job_list.html
    │   ├── tests.py
    │   ├── urls.py
    │   ├── views.py
    ├── settings.py
    ├── templates
    │   ├── base.html
    │   └── index.html
    ├── urls.py
    └── wsgi.py

     jobs是一个application,index.py是首页入口,项目下的templates目录放全局template,包括首页index.html及公共模板base.html。

    首先,Django的模板查找顺序在项目的settings.py定义:

     TEMPLATE_LOADERS = ( 

        'django.template.loaders.filesystem.Loader',
        'django.template.loaders.app_directories.Loader',
    #     'django.template.loaders.eggs.Loader',
    )

    以上设置表明先从文件目录找,如果找不到就从每个application下的templates文件夹下找。

    而文件目录又是如下定义:

     TEMPLATE_DIRS = (
        # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
        # Always use forward slashes, even on Windows.
        # Don't forget to use absolute paths, not relative paths.
        '/home/andrew/hg_repo/Django/Django/templates',
    )

    jobs中使用jinja2的模板,views.py代码如下:

    from django.http import HttpResponse
    from django.conf import settings
    from jinja2 import Environment, PackageLoader, FileSystemLoader, ChoiceLoader
    from Django.jobs.models import Job
    def job_list(request):    
        loader = ChoiceLoader([
            FileSystemLoader(settings.TEMPLATE_DIRS),
            PackageLoader('Django.jobs', 'templates')
        ])
        env = Environment(loader=loader)
        template = env.get_template('job_list.html')
        object_list = Job.objects.all()
        return HttpResponse(
            template.render(object_list=object_list)
        )

     ChoiceLoader根据顺序找模板,原理和Django的TEMPLATE_LOADERS类似,加FileSystemLoader(settings.TEMPLATE_DIRS)的目的是为了找到项目的templates


  • 相关阅读:
    C# 利用StringBuilder提升字符串拼接性能
    T420 开启麦克风
    理解数据库中的undo日志、redo日志、检查点
    网络编程api总结
    源码剖析Linux epoll实现机制及Linux上惊群
    linux信号的处理--部分源码分析
    git使用笔记-提高篇-重置揭密
    git使用笔记-比较分支差异
    git使用笔记-提高篇
    ubuntu安装软件依赖解决
  • 原文地址:https://www.cnblogs.com/children/p/3023733.html
Copyright © 2011-2022 走看看