0

如果时间不是 09:00 到 17:00 之间的工作日,我想在我的模板 (base.html) 中隐藏一个块。

我在想类似的东西(非常简化):

{% if now is 09:00 and 17:00 on weekdays %}

#Show callback form

{% else %}

#We do not answer the phone before 09:00 and after 17:00 

{% endif %}

可能吗?

4

2 回答 2

1

我建议在你的view.py

import datetime

# In view
now = datetime.datetime.now()
call_us_now = False
if 9 < now.hour < 17:
   call_us_now = True

# Send 'call_us_now' to context

.

{# In template #}
{% if call_us_now %}
    {# Show callback form #}
{% else %}
    {# We do not answer the phone before 09:00 and after 17:00 #}
{% endif %]
于 2013-04-25T12:23:10.193 回答
1

我想在我的 base.html 上使用这个代码,所以在每个视图上实现你的代码可能有点困难?

写一个自定义template context processor。您可以以此为起点:

from datetime import datetime, time

from django.conf import settings

def calling_flag(request):
    """ Sets the flag in the template if the current time is between CALL_HOURS """
    if settings.CALL_HOURS:
        now = datetime.now().time()
        start_time,end_time = settings.CALL_HOURS
        start_time = time(start_time[:2],start_time[-2:])
        end_time = time(end_time[:2],end_time[-2:])
        return {'IN_TIME': start_time <= now <= end_time}

将其保存在应用程序内的文件中。假设应用程序被调用feedback,并且您将上述代码放在目录中调用的文件custom_template_flags.pyfeedback。下一步,将其添加到您的settings.py

TEMPLATE_CONTEXT_PROCESSORS = (
    # -- your other context processors
    'feedback.custom_template_flags.calling_flag',
)

最后,再次添加您的时间范围settings.py

CALL_HOURS = ('0900','1700')

现在,所有模板都将{{ IN_TIME }}具有TrueFalse

于 2013-04-25T14:42:25.803 回答