开发者

Use 'now' in django blocktrans?

I'd like to add the year into a Django blocktrans - using the syntax below.

{% blocktrans with now|date:"Y" as copydate %}
     &co开发者_StackOverflow社区py; {{ copydate }} Company
{% endblocktrans %}

This is similar to this existing Django ticket (http://code.djangoproject.com/ticket/3088), which apparently should work now but I can't get to work either.

In both cases the tag is simply not expanded, but the rest of the blocktrans renders fine.


The only way is to get your date in python and use date filter as Reiner proposes or define your own templatetag. You can create a little context processors to set date in your context.

def my_date(request):
  import datetime
  return {'my_date':datetime.datetime.now()}

and add this in settings.py

TEMPLATE_CONTEXT_PROCESSORS = DEFAULT_SETTINGS.TEMPLATE_CONTEXT_PROCESSORS + (
      'the_package_of_my_tiny_function.my_date',
      )

Use it in your templates like this:

   {% blocktrans with my_date|date:"Y" as copydate %}
      © {{ copydate }} Company
   {% endblocktrans %}

Don't forget to pass RequestContext as context_instance in your views

Here is the example.


Starting from Django 1.8, you can now use the {% now 'Y' as copydate %} syntax, so you should be able to do:

{% now 'Y' as copydate %}
{% blocktrans %}© {{ copydate }} Company{% endblocktrans %}

Source: https://docs.djangoproject.com/en/dev/ref/templates/builtins/#now


The now tag returns a formatted date as string matching the format passed. date probably needs a datetime/date object. So chaining these together wouldn't work.

I'm not even sure if you can use the now tag in the with statement, but try this.

{% blocktrans with now "Y" as copydate %}

now accepts the same format string as date. If this doesn't work either, my best bet would be to just pass the template a datetime.datetime.now() result, and use that instead of now.

{% blocktrans with my_date|date:"Y" as copydate %}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜