django中如何使用template_processors避免频繁的函数传递给html,使用template上下文的方法传递方法

首先引起这个方法思考的是文件的访问和传递,在django上传图片的时候,会有很多app和很多view

这就会出现一个问题,如果多个html中都需要访问文件、照片,显然会造成一个频繁的参数传递。

此时出现了一个方案:

就拿刚刚的图片访问做举例,先在Setting中设置其目录为media

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')

其次,在setting.py的TEMPLATES中content_processors下添加

djando.template.context_processors.media

'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',
        'django.template.context_processors.media',#通过这个方法把media注入到每个html页面中(自定义方法注入到html中)
    ],

咱们可以访问一个这个方法的源码。

def media(request):
    """
    Add media-related context variables to the context.
    """
    return {'MEDIA_URL': settings.MEDIA_URL}

这个方法实现了一个功能,就是返回了MEDIA的路径,并且应用于template的上下文中,使得在任何html文件中兼可以访问这个路径。

可以看到,源码内还有STATIC的方法

def static(request):
    """
    Add static-related context variables to the context.
    """
    return {'STATIC_URL': settings.STATIC_URL}

还包括了每个表单中必定使用的csrf_token

def csrf(request):
    """
    Context processor that provides a CSRF token, or the string 'NOTPROVIDED' if
    it has not been provided by either a view decorator or the middleware
    """
    def _get_val():
        token = get_token(request)
        if token is None:
            # In order to be able to provide debugging info in the
            # case of misconfiguration, we use a sentinel value
            # instead of returning an empty dict.
            return 'NOTPROVIDED'
        else:
            return token

    return {'csrf_token': SimpleLazyObject(_get_val)}

再返回上一级看包括大家常用的request对象

def request(request):
    return {'request': request}

如果在以后有需要应用于所有页面的一个方法,就可以通过重写和在template_context中调用的方法应用于所有的html页面中

发布了63 篇原创文章 · 获赞 0 · 访问量 1205

猜你喜欢

转载自blog.csdn.net/qq_37463791/article/details/103607884
今日推荐