如何在Django模板中显示当前年份?

问题:如何在Django模板中显示当前年份?

什么是内置模板标签以动态显示当前年份。像“ 2011”一样,显示该模板的模板标记是什么?

What is the inbuilt template tag to display the present year dynamically. Like “2011” what would be the template tag to display that?


回答 0

仅打印当前年份的完整标签是{% now "Y" %}。请注意,Y必须用引号引起来。

The full tag to print just the current year is {% now "Y" %}. Note that the Y must be in quotes.


回答 1

{% now 'Y' %} 是正确的语法

{% now 'Y' %} is the correct syntax


回答 2


回答 3

我在基于Django的网站http://pmtboyshostelraipur.pythonanywhere.com/中使用了以下命令,该工具可以正常运行(也许,当您阅读本文时,它已经停止工作,因为这是免费托管,所以试试看代码)。

{% now 'Y' %}

您可以使用以下代码在我显示了本年度的页脚部分中访问和查看(省略CSS部分,因此请使用您自己的)。

<footer class="container-fluid" id="footer">
    <center>
        <p>
           &copy;
           {% now 'Y' %}, 
           PMT Boys hostel <br> 
           All rights reserved
        </p>
    </center>
</footer>

它在我的网站的页脚中显示以下居中文本。

©2018, PMT Boys hostel 
All rights reserved

I have used the following in my Django based website http://pmtboyshostelraipur.pythonanywhere.com/ which works fine as expected (Maybe, by the time you’re reading this post, it would have stopped working because that’s a free hosting so just try in code and see).

{% now 'Y' %}

You can visit & see it in the footer part where I have displayed the current year using the below code(CSS part is omitted so use your own).

<footer class="container-fluid" id="footer">
    <center>
        <p>
           &copy;
           {% now 'Y' %}, 
           PMT Boys hostel <br> 
           All rights reserved
        </p>
    </center>
</footer>

And it is displaying the following centred text in my website’s footer.

©2018, PMT Boys hostel 
All rights reserved

回答 4

在我的模板中,除了当年之外,我还需要一个具有20个值(从当年开始)的信用卡到期年份下拉菜单。在select需要的值是2位和显示字符串4个位数。为了避免复杂的模板代码,我编写了这个简单的模板标签:

@register.filter
def add_current_year(int_value, digits=4):
    if digits == 2:
        return '%02d' % (int_value + datetime.datetime.now().year - 2000)
    return '%d' % (int_value + datetime.datetime.now().year)

并以以下方式使用它:

<select name="card_exp_year">
    {% for i in 'iiiiiiiiiiiiiiiiiiii' %}
    <option value="{{ forloop.counter0|add_current_year:2 }}">{{ forloop.counter0|add_current_year:4 }}</option>
    {% endfor %}
</select>

In my template, aside from the current year, I needed a credit card expiration year dropdown with 20 values (starting with the current year). The select values needed to be 2 digits and the display strings 4 digits. To avoid complex template code, I wrote this simple template tag:

@register.filter
def add_current_year(int_value, digits=4):
    if digits == 2:
        return '%02d' % (int_value + datetime.datetime.now().year - 2000)
    return '%d' % (int_value + datetime.datetime.now().year)

And used it in the following manner:

<select name="card_exp_year">
    {% for i in 'iiiiiiiiiiiiiiiiiiii' %}
    <option value="{{ forloop.counter0|add_current_year:2 }}">{{ forloop.counter0|add_current_year:4 }}</option>
    {% endfor %}
</select>