如何在Django模板中显示本地内存缓存?
在Django模板中显示本地内存缓存的可行方法
方法一:在视图中获取缓存并传入模板上下文
直接在视图函数里调用cache.get()取出缓存内容,再通过render函数的上下文参数传递给模板,模板中直接用变量名渲染即可。视图代码(views.py):
from django.core.cache import cache from django.shortcuts import render def index(request): # 第二个参数为默认值,避免缓存不存在时返回None message = cache.get("message", "") return render(request, "index.html", {"message": message})模板代码(index.html):
{{ message }}方法二:自定义模板标签
要是需要在多个模板里频繁获取缓存内容,可以自定义一个简单的模板标签,实现模板内直接调用获取指定缓存键的功能。实现步骤:
- 在你的Django应用下创建
templatetags目录(必须包含__init__.py空文件),新建cache_tags.py文件:
from django import template from django.core.cache import cache register = template.Library() @register.simple_tag def get_cache(key, default=""): return cache.get(key, default)- 在模板中加载自定义标签并使用:
{% load cache_tags %} {% get_cache "message" %}- 在你的Django应用下创建
内容的提问来源于stack exchange,提问作者Super Kai - Kazuya Ito
相关产品推荐
相关产品推荐

