7

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.

3 Answers 3

10

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.

1
  • 1
    Hi Miga, I've marked this as the best answer, but could you expand the answer above to include the full example from your blog? Thanks. Mar 3, 2011 at 9:57
6

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

1

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 %}
3
  • Thanks Reiner! 1. 'with now "Y" as copydate' isn't proper syntax, it seems you need a template filter. 2. Would work, but I'd rather not pass every template the date explicitly. 3. Won't work as 'blocktrans' doesn't allow other block tags inside it. Thanks again for responding though. Feb 8, 2011 at 11:14
  • @nailer Ah thank you, I removed that suggestion. Did you try the other by any chance? Feb 8, 2011 at 11:16
  • Reiner: yep, updated my comment above for the other suggestions. Feb 8, 2011 at 11:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.