在Django模板Django中获取特定日期 [英] get particular date in django template Django
问题描述
我需要在我的django模板文件中检查每个月的10号,有人可以告诉我如何检查这个
吗?我需要在每个月10号之前显示一些数据,并在10号之后隐藏该数据
Hi i need to check the 10th of each month in my django template file , can anybody tell me how can i check this accentually i need to show some data before the 10th of each month and hide that after 10th
推荐答案
需要理解的几件事:
- Django的模板语言并不是真正围绕真实程序设计的。
- 它不支持真正的表达式。
- …但它确实支持基本条件和循环。
- 因此,您可以检查一个值是否等于或大于或小于另一个。值,您不能做更多的事情。
- 除非您使用过滤器或自定义模板标签。
- 过滤器可以从一件事到另一件事。
- 模板标签可以执行更复杂的操作,这超出了此问题的范围。
- 虽然过滤器或自定义模板标签都可以
- Django's templating language isn't really designed around "real" programming. At it's core, it's just building strings.
- It doesn't support real "expressions".
- …but it does support basic conditionals and loops.
- So while you can check if a value is equal to or greater than or less than another value, you can't do much more than that.
- Unless you use a filter or a custom template tag.
- Filters can transform values from one thing to another.
- Template tags can do way more complicated things, that are beyond the scope of this question.
- While either a filter or a custom template tag could get where you want to go, they'd be overkill.
所以,在我看来,最简单的方法是到:
So, in my opinion, the easiest way to do this would be to:
- 计算视图中当前日期。
- 将该值传递给您的模板。
- 对数字10进行简单的如果大于检查传入的值。
因此,我们的视图将类似于:
So, our view would look something like:
def sample_view(request, *args, **kwargs):
from datetime import date
current_date = date.today()
current_day = int(current_date.day) # force a cast to an int, just to be explicit
return render_to_response("template", {'day_of_the_month': current_day })
在我们的模板中:
{% if day_of_the_month > 10 %}
<!-- Stuff to show after the 10th -->
{% else %}
<!-- Stuff to show before the 10th -->
{% endif %}
这确实使您可能隐藏的模板暴露了东西出于安全原因在日期。 您永远不应基于if / then检查在模板中隐藏安全的东西。
This does expose stuff to your template you might be hiding based on the date for security reasons. You should never hide secure things in a template based on an if/then check.
如果您需要进行其他检查,则可以传入 current_date
,并对照数字10检验 current_date.day
,而不是在当日明确传递。它会不太明确,但会更加通用和灵活。
If you need to do additional checks, you could just pass in current_date
, and check current_date.day
against the number 10 instead of specifically passing in that day. It'd be less explicit, but more generic and flexible.
这篇关于在Django模板Django中获取特定日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!