0

I have a template tag to generate the url as follows;

<li><a href="{% url 'blog_archive' year='2013' %}">Archive</a></li>

I want the '2013'(year) to be generated automatically based off the current year. There is a tag that can do this {% now 'Y' %} however i cannot use it inside the existing template tag as it just produces errors.

Do i need to create a custom tag to do this?

4

3 回答 3

1

可能更好的决定是将默认参数设置在urls.py?

示例urls.py

from django.utils.timezone import now
...
urlpatterns = patterns('app.views',
    url(r'^.../$', 'blog_archive', {'year': now().strftime('%Y')}),
)
于 2013-06-28T13:28:14.423 回答
0

就是你想要的。

也许是这样:

<li><a href="{% url 'blog_archive' year=value|date:"Y"  %}">Archive</a></li>
# just pass the datetime object as 'value'
于 2013-06-28T12:18:03.583 回答
0

像这样在另一个标签中包含一个标签是不可能的。

您可以创建一个赋值标签,它将标签的结果存储在上下文变量中,而不是输出它。

文档中的示例分配标签用于模板标签get_current_time,您可以使用它来代替{% now %}标签。

在您的mytags.py模板标签模块中:

from django import template

register = template.Library()

@register.assignment_tag
def get_current_time(format_string):
    return datetime.datetime.now().strftime(format_string)

在您的模板中:

{% load mytags %}
{% get_current_time "%Y" as year %}
<li><a href="{% url 'blog_archive' year=year %}">Archive</a></li>
于 2013-06-28T13:15:37.137 回答