Ticket #16332: i18n_urls.diff

File i18n_urls.diff, 5.9 KB (added by Florian Apolloner, 13 years ago)
  • django/templatetags/i18n.py

    diff -r af6aa15ae9bf django/templatetags/i18n.py
    a b  
     1from __future__ import with_statement
    12import re
    23
    34from django.template import Node, Variable, VariableNode
     
    67from django.template.base import _render_value_in_context
    78from django.utils import translation
    89from django.utils.encoding import force_unicode
    9 from django.template.defaulttags import token_kwargs
     10from django.template.defaulttags import token_kwargs, kwarg_re, URLNode
    1011
    1112register = Library()
    1213
     
    117118        context.pop()
    118119        return result % data
    119120
     121class I18NURLNode(URLNode):
     122    def __init__(self, view_name, language, args, kwargs, asvar):
     123        super(I18NURLNode, self).__init__(view_name, args, kwargs, asvar, False)
     124        self.language = language
     125
     126    def render(self, context):
     127        with translation.override(self.language.resolve(context)):
     128            return super(I18NURLNode, self).render(context)
     129
    120130@register.tag("get_available_languages")
    121131def do_get_available_languages(parser, token):
    122132    """
     
    366376
    367377    return BlockTranslateNode(extra_context, singular, plural, countervar,
    368378            counter)
     379
     380@register.tag
     381def i18n_url(parser, token):
     382    bits = token.split_contents()
     383    if len(bits) < 3:
     384        raise TemplateSyntaxError("'%s' takes at least two arguments"
     385                                  " (path to a view and the language)" % bits[0])
     386    viewname = parser.compile_filter(bits[1])
     387    language = parser.compile_filter(bits[2])
     388    args = []
     389    kwargs = {}
     390    asvar = None
     391    bits = bits[3:]
     392    if len(bits) >= 2 and bits[-2] == 'as':
     393        asvar = bits[-1]
     394        bits = bits[:-2]
     395
     396    if len(bits):
     397        for bit in bits:
     398            match = kwarg_re.match(bit)
     399            if not match:
     400                raise TemplateSyntaxError("Malformed arguments to url tag")
     401            name, value = match.groups()
     402            if name:
     403                kwargs[name] = parser.compile_filter(value)
     404            else:
     405                args.append(parser.compile_filter(value))
     406
     407    return I18NURLNode(viewname, language, args, kwargs, asvar)
  • docs/topics/http/urls.txt

    diff -r af6aa15ae9bf docs/topics/http/urls.txt
    a b  
    2828mappings. And, because it's pure Python code, it can be constructed
    2929dynamically.
    3030
     31Additionally Django allows to translate URLs according to the active language.
     32This process is described in the :ref:`internationalization docs <url-internationalization>`.
     33
    3134.. _how-django-processes-a-request:
    3235
    3336How Django processes a request
  • docs/topics/i18n/internationalization.txt

    diff -r af6aa15ae9bf docs/topics/i18n/internationalization.txt
    a b  
    887887    that a carelessly translated URL causes a collision with a non-translated
    888888    URL pattern.
    889889
     890.. _reversing_in_templates:
     891
     892Reversing in tepmlates
     893----------------------
     894
     895If localized URLs get reversed in templates the always use the current language.
     896To link to an URL in another language an extra tag got added:
     897
     898.. code-block:: html+django
     899
     900    {% load i18n %}
     901    {% get_available_languages as languages %}
     902    View the Homepage in:
     903    {% for lang in languages %}
     904        <a href="{% i18n_url 'homepage' lang.0 kwarg1=val1 kwarg2=val2 %}">{{ lang.1 }}</a>
     905    {% endfor %}
     906
     907The ``i18n_url`` tag expects the language after the viewname and otherwise
     908like the builtin ``url`` tag.
     909
    890910.. _set_language-redirect-view:
    891911
    892912The ``set_language`` redirect view
  • tests/regressiontests/i18n/patterns/tests.py

    diff -r af6aa15ae9bf tests/regressiontests/i18n/patterns/tests.py
    a b  
    66from django.core.urlresolvers import reverse, clear_url_caches
    77from django.test import TestCase
    88from django.test.utils import override_settings
     9from django.template import Template, Context
    910from django.utils import translation
    1011
    1112
     
    241242        self.assertEqual(response.status_code, 200)
    242243        self.assertEqual(response['content-language'], 'pt-br')
    243244        self.assertEqual(response.context['LANGUAGE_CODE'], 'pt-br')
     245
     246
     247class URLTagTests(URLTestCaseBase):
     248    """
     249    Test if the i18n_url tag works.
     250    """
     251    def test_strings_only(self):
     252        c = Context({})
     253        t = Template("""{% load i18n %}
     254                {% i18n_url 'no-prefix-translated' 'nl' %}
     255                {% i18n_url 'no-prefix-translated' 'pt-br' %}""")
     256        self.assertEqual(t.render(c).strip().split(),
     257                         [u'/vertaald/', u'/traduzidos/'])
     258
     259    def test_context(self):
     260        c = Context({'url': 'no-prefix-translated', 'lang1':'nl',
     261                     'lang2':'pt-br'})
     262        t = Template("""{% load i18n %}
     263                {% i18n_url url lang1 %}
     264                {% i18n_url url lang2 %}""")
     265        self.assertEqual(t.render(c).strip().split(),
     266                         [u'/vertaald/', u'/traduzidos/'])
     267
     268    def test_args_and_kwargs(self):
     269        c = Context({})
     270        t = Template("""{% load i18n %}
     271                {% i18n_url 'no-prefix-translated-slug' 'nl' 'apo' %}
     272                {% i18n_url 'no-prefix-translated-slug' 'pt-br' 'apo' %}""")
     273        self.assertEqual(t.render(c).strip().split(),
     274                         [u'/vertaald/apo/', u'/traduzidos/apo/'])
     275        t = Template("""{% load i18n %}
     276                {% i18n_url 'no-prefix-translated-slug' 'nl' slug='apo' %}
     277                {% i18n_url 'no-prefix-translated-slug' 'pt-br' slug='apo' %}""")
     278        self.assertEqual(t.render(c).strip().split(),
     279                         [u'/vertaald/apo/', u'/traduzidos/apo/'])
     280
Back to Top