我有fb或twitter上的通知滾動條。頂部的menu.html是直接包含在base.html Unfortunatelly中,我只能在那裏使用User方法。是否可以不寫每個視圖我需要通知?我想要在一個視圖中粘貼一次,並將其始終保存在頂層menu.html中!在base.html中查看django
from intarface import menu_nots
nots = menu_nots(request)
我有fb或twitter上的通知滾動條。頂部的menu.html是直接包含在base.html Unfortunatelly中,我只能在那裏使用User方法。是否可以不寫每個視圖我需要通知?我想要在一個視圖中粘貼一次,並將其始終保存在頂層menu.html中!在base.html中查看django
from intarface import menu_nots
nots = menu_nots(request)
這是可能的。嘗試writing your own context processor。
def add_notifications(request):
""" Adds Facebook notifications to the view context. """
return {'notifications': menu_nots(request)}
接下來,將它添加到settings.py中的TEMPLATE_CONTEXT_PROCESSORS。
我認爲最好的方式通過使用包含標籤解決您的問題: https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#inclusion-tags
@register.inclusion_tag('menu.html')
def show_menu():
#menu logic2
在base.html文件:
<html>
...
{% show_menu %}
...
</html>
包含標籤的功能將在每次請求運行每頁
使用messages%用戶名%!
視圖
from django.contrib import messages
messages.add_message(request, messages.INFO, 'Hello world.')
messages.debug(request, '%s SQL statements were executed.' % count)
messages.info(request, 'Three credits remain in your account.')
messages.success(request, 'Profile details updated.')
messages.warning(request, 'Your account expires in three days.')
messages.error(request, 'Document deleted.')
模板
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}