Wednesday, 2 March 2011

Having global variable in your django templates

This post is based on question in stackoverflow.com
The question is about having 'now' in blocktrans.
In blocktrans we can't use templatetags so we will assign result of the templatetags to a variable, like this:
 {% url "add_account" as add_account_url %}

But 'now' doesn't act the same way.

{% now "Y" as my_date %} will print the year and my_date will be empty.
If you want to have date in your blocktrans you need to define variable in python and pass it to the template.
This is not so handy. Not every view will send date in the context.
But there is hope.
1. Define a tiny function:

def my_date(request):
   import datetime
   return {'my_date':datetime.datetime.now()}
2. Put this function in your TEMPLATE_CONTEXT_PROCESSORS like this:

    TEMPLATE_CONTEXT_PROCESSORS = DEFAULT_SETTINGS.TEMPLATE_CONTEXT_PROCESSORS + (
      'django.core.context_processors.request',
      'the_package_of_my_tiny_function.my_date',
      )


3. 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.

No comments:

Post a Comment