Rya*_*ery 2 python django django-templates
假设我有一个django站点,以及一个带有页脚的所有页面的基本模板,我想在我的站点上显示前5个产品的列表.我该如何将该列表发送到基本模板进行渲染?每个视图是否都需要将该数据发送到render_to_response?我应该使用template_tag吗?你会怎么做?
您应该使用自定义上下文处理器.有了这个,您可以设置一个变量,例如top_products可以在所有模板中使用的变量.
例如
# in project/app/context_processors.py
from app.models import Product
def top_products(request):
return {'top_products': Products.objects.all()} # of course some filter here
Run Code Online (Sandbox Code Playgroud)
在你的settings.py:
TEMPLATE_CONTEXT_PROCESSORS = (
# maybe other here
'app.context_processors.top_products',
)
Run Code Online (Sandbox Code Playgroud)
在您的模板中:
{% for product in top_products %}
...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1180 次 |
| 最近记录: |