Permalink
Browse files

Added templatetag language, took it out of Django 1.4 with some changes

  • Loading branch information...
1 parent 8322534 commit d97ba91850359f699f6de4ffc26fe87ef3915d58 @hvdklauw hvdklauw committed Dec 15, 2011
Showing with 55 additions and 0 deletions.
  1. 0 i18nurls/templatetags/__init__.py
  2. +55 −0 i18nurls/templatetags/i18nurls.py
No changes.
@@ -0,0 +1,55 @@
+from django import template
+from django.utils import translation
+
+register = template.Library()
+
+
+class override(object):
+ def __init__(self, language, deactivate=False):
+ self.language = language
+ self.deactivate = deactivate
+ self.old_language = translation.get_language()
+
+ def __enter__(self):
+ if self.language is not None:
+ translation.activate(self.language)
+ else:
+ translation.deactivate_all()
+
+ def __exit__(self, exc_type, exc_value, traceback):
+ if self.deactivate:
+ translation.deactivate()
+ else:
+ translation.activate(self.old_language)
+
+
+class LanguageNode(template.Node):
+ def __init__(self, nodelist, language):
+ self.nodelist = nodelist
+ self.language = language
+
+ def render(self, context):
+ with override(self.language.resolve(context)):
+ output = self.nodelist.render(context)
+ return output
+
+
+@register.tag
+def language(parser, token):
+ """
+ This will enable the given language just for this block.
+
+ Usage::
+
+ {% language "de" %}
+ This is {{ bar }} and {{ boo }}.
+ {% endlanguage %}
+
+ """
+ bits = token.split_contents()
+ if len(bits) != 2:
+ raise template.TemplateSyntaxError("'%s' takes one argument (language)" % bits[0])
+ language = parser.compile_filter(bits[1])
+ nodelist = parser.parse(('endlanguage',))
+ parser.delete_first_token()
+ return LanguageNode(nodelist, language)

0 comments on commit d97ba91

Please sign in to comment.