开发者

How to display the current year in a Django template?

开发者 https://www.devze.com 2023-03-10 16:41 出处:网络
What is the inbuilt template tag to display the present year dynami开发者_高级运维cally. Like \"2011\" what would be the template tag to display that?The full tag to print just the current year is {%

What is the inbuilt template tag to display the present year dynami开发者_高级运维cally. Like "2011" what would be the template tag to display that?


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


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


{% now %}


I have used the following in my Django based website

{% 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


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>
0

精彩评论

暂无评论...
验证码 换一张
取 消