Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 %}
     © {{ 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.

like image 454
mikemaccana Avatar asked Feb 08 '11 10:02

mikemaccana


3 Answers

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.

like image 54
miga Avatar answered Nov 18 '22 09:11

miga


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

like image 6
Baptiste M. Avatar answered Nov 18 '22 07:11

Baptiste M.


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 %}
like image 1
Reiner Gerecke Avatar answered Nov 18 '22 07:11

Reiner Gerecke