zoukankan      html  css  js  c++  java
  • 上下文渲染器RequestContext

    在render_to_response中加RequestContext会将settings中设置的context_processors返回值收集起来传到模板
    return render_to_response('index.html', {...}, context_instance=RequestContext(request))

    settings.py

    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [os.path.join(BASE_DIR, 'templates')]
            ,
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                    'BookStore.views.global_settings',
                    'django.template.context_processors.media',
                    'BookStore.context_processor.ip_address',
    
                ],
            },
        },


    可以手动写个上下文渲染器(以下摘自自强学堂):新建context_processor.py

    添加以下内容

     
    def ip_address(request):
        return {'ip_address': request.META['REMOTE_ADDR']}
    settings.py中加入对应路径,如上面的settings.py加入了'BookStore.context_processor.ip_address'

     在模板中就可以使用

    {{ ip_address }}

    https://lincolnloop.com/blog/2008/may/10/getting-requestcontext-your-templates/

    这里有如何向render_to_response添加RequestContext的方法。

    有个@render_to感觉非常经典,代码如下

    def render_to(template_name):
        def renderer(func):
            def wrapper(request, *args, **kw):
                output = func(request, *args, **kw)
                if not isinstance(output, dict):
                    return output
                return render_to_response(request, template_name, output)
            return wrapper
        return renderer
    
    @render_to('my_template.html')
    def my_view(request):
        # View code here...
        return some_dict
  • 相关阅读:
    GDB常用命令总结
    进程使用的文件描述符fd值达到最大值引起的问题
    RedHat静态Ip地址配置
    Hotspot JVM默认垃圾收集器
    JVM常用参数及调优
    spring-boot定制和优化内嵌的Tomcat
    平面设计技能
    docker 虚悬镜像
    Linux 常用命令
    同步、异步、阻塞、非阻塞
  • 原文地址:https://www.cnblogs.com/songbird/p/7492420.html
Copyright © 2011-2022 走看看