Login

Custom Template Tag - No Translate

Author:
robcharlwood
Posted:
April 14, 2010
Language:
Python
Version:
1.1
Score:
0 (after 0 ratings)

Forces Django not to translate built in template tags and filters. If you have a multi-lingual site but certain parts of it are not all translated, you can use this snippet to force Django to bypass translation on all template tags and filters so things like dates aren't randomly translated whilst everything else is not.

For example:

{% notrans %}{{download.doc|filesizeformat}}{% endnotrans %}

This snippet including the filesizeformat template tag would not be translated.

Mega thanks goes out to Dan Fairs for all his help on this!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
from django.utils import translation

def force_no_translation(parser, token):
    nodelist = parser.parse(('endnotrans',))
    parser.delete_first_token()
    return NoTransNode(nodelist)

class NoTransNode(template.Node):
    
    def __init__(self, nodelist):
        self.nodelist = nodelist
        
    def render(self, context):
        language = translation.get_language()
        translation.deactivate()
        output = self.nodelist.render(context)
        translation.activate(language)
        return output

register.tag('notrans', force_no_translation)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

mk (on April 15, 2010):

Shouldn't you use language = translation.get_language() on line 14, so you don't require the request in the context?

#

robcharlwood (on April 15, 2010):

That's quite a good point actually MK,

I am sure I did it like this for a reason but I think it was project specific and so I can update this snippet once I have tested it.

Regards,

Rob

#

Please login first before commenting.