Login

Custom Template Tag - No Translate

Author:
robcharlwood
Posted:
April 14, 2010
Language:
Python
Version:
1.1
Tags:
translation multi-lingual custom-template-tags
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 range filter by zalun 5 years, 12 months ago
  2. RelatedNullFilterSpec: django-admin custom filter all/null/not null/choices by Codeko 4 years, 4 months ago
  3. mkrange - create a range() inside a template - variable/filter support for range values by berserkpi 4 years, 6 months ago
  4. Extended i18n base model by alcinnz 1 year, 10 months ago
  5. Modeli18n by pavl 4 years, 9 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.