Commits

Anonymous committed c9f2048

Added translate_url tag

Comments (0)

Files changed (2)

 Note that non-translated fields from the original model are not copied to the
 translation. For non-translated fields, always use the original.
 
+``{% translate_url [path] [language] %}`` tag
+---------------------------------------------
+
+If you are using i18n in your URLs, you may sometimes need to obtain a
+translated URL. This tag gives you that ability. The tag accepts an optional
+path parameter which defaults to the current path. You must wrap it in the
+Djago's built-in ``{% language %}`` tag to get translations for different
+languages or use the language parameter. Here is an example::
+
+    {% language 'es' %}
+    {% translate_url %} current URL in Spanish
+    {% endlanguage %}
+
+    {% translate_url language='es' %} Same as above
+
+    {% language 'es' %}
+    {% translate_url object.get_absolute_path %} Object's URL in Spanish
+    {% endlanguage %}
+
+    {% translate_url object.get_absolute_path 'es' %} Same as above
+
 .. _django-hvad: http://django-hvad.readthedocs.org/en/latest/index.html
 .. _django-modeltranslation: https://github.com/deschler/django-modeltranslation
 .. _django-lingua: http://code.google.com/p/django-lingua/

i18n_model/templatetags/i18n_model.py

 from __future__ import unicode_literals
 
 from django.template import Library
-from django.utils.translation import get_language
+from django.utils.translation import get_language, override
+from django.core.urlresolvers import reverse, resolve
 
 register = Library()
 
     try:
         return obj.translations.lang(language).get()
     except:
-        return obj
+        return obj
+
+
+@register.simple_tag(takes_context=True)
+def translate_url(context, path=None, language=None):
+    try:
+        if path:
+            url = resolve(path)
+        else:
+            url = context['request'].resolver_match
+    except:
+        return ''
+
+    language = language or get_language()
+
+    # We need to call override here because the override from the {% language %}
+    # tag doesn't affect the reverse() call for some reason.
+    with override(language):
+        url_full_name = url.url_name
+        if url.namespace:
+            url_full_name = '%s:%s' % (url.namespace, url_full_name)
+        return reverse(url_full_name, args=url.args, kwargs=url.kwargs)