Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

i18n: updated unittests and fixed bugs in the tags, removed the old t…

…ags and fixed #719 (thx nesh)

git-svn-id: http://code.djangoproject.com/svn/django/branches/i18n@1064 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit 1470bb0b2391028e00ea1eb95eca7c90e12b004c 1 parent ed05d90
authored
98  django/core/template/defaulttags.py
@@ -290,63 +290,6 @@ def render(self, context):
290 290
             return ''
291 291
         return str(int(round(ratio)))
292 292
 
293  
-class GetAvailableLanguagesNode(Node):
294  
-
295  
-    def __init__(self, variable):
296  
-        self.variable = variable
297  
-
298  
-    def render(self, context):
299  
-        from django.conf.settings import LANGUAGES
300  
-        context[self.variable] = LANGUAGES
301  
-        return ''
302  
-
303  
-class I18NNode(Node):
304  
-
305  
-    def __init__(self, cmd):
306  
-        self.cmd = cmd
307  
-        self.i18n_re = re.compile(r'^\s*(_|gettext|gettext_noop)\((.*)\)\s*$')
308  
-        self.ngettext_re = re.compile(r'''^\s*ngettext\(((?:".+")|(?:'.+')|(?:""".+"""))\s*,\s*((?:".+")|(?:'.+')|(?:""".+"""))\s*,\s*(.*)\)\s*$''')
309  
-
310  
-    def _resolve_var(self, s, context):
311  
-        if s.startswith("'") and s.endswith("'"):
312  
-            s = s[1:-1]
313  
-        elif s.startswith('"""') and s.endswith('"""'):
314  
-            s = s[3:-3]
315  
-        elif s.startswith('"') and s.endswith('"'):
316  
-            s = s[1:-1]
317  
-        else:
318  
-            s = resolve_variable_with_filters(s, context)
319  
-        return s
320  
-
321  
-    def render(self, context):
322  
-        m = self.i18n_re.match(self.cmd)
323  
-        if m:
324  
-            f = m.group(1)
325  
-            s = self._resolve_var(m.group(2), context)
326  
-            if f in ('_', 'gettext'):
327  
-                return translation.gettext(s) % context
328  
-            elif f == 'gettext_noop':
329  
-                return translation.gettext_noop(s) % context
330  
-            else:
331  
-                raise TemplateSyntaxError("i18n only supports _, gettext, gettext_noop and ngettext as functions, not %s" % f)
332  
-        m = self.ngettext_re.match(self.cmd)
333  
-        if m:
334  
-            singular = self._resolve_var(m.group(1), context)
335  
-            plural = self._resolve_var(m.group(2), context)
336  
-            var = resolve_variable_with_filters(m.group(3), context)
337  
-            return translation.ngettext(singular, plural, var) % context
338  
-        raise TemplateSyntaxError("i18n must be called as {% i18n _('some message') %} or {% i18n ngettext('singular', 'plural', var) %}")
339  
-
340  
-        cyclevars = [v for v in args[1].split(",") if v]    # split and kill blanks
341  
-        name = args[3]
342  
-        node = CycleNode(cyclevars)
343  
-
344  
-        if not hasattr(parser, '_namedCycleNodes'):
345  
-            parser._namedCycleNodes = {}
346  
-
347  
-        parser._namedCycleNodes[name] = node
348  
-        return node
349  
-
350 293
 def do_comment(parser, token):
351 294
     """
352 295
     Ignore everything between ``{% comment %}`` and ``{% endcomment %}``
@@ -813,45 +756,6 @@ def do_widthratio(parser, token):
813 756
         raise TemplateSyntaxError("widthratio final argument must be an integer")
814 757
     return WidthRatioNode(this_value_var, max_value_var, max_width)
815 758
 
816  
-def do_get_available_languages(parser, token):
817  
-    """
818  
-    This will store a list of available languages
819  
-    in the context.
820  
-
821  
-    Usage is as follows::
822  
-
823  
-        {% get_available_languages as languages %}
824  
-        {% for language in languages %}
825  
-        ...
826  
-        {% endfor %}
827  
-
828  
-    This will just pull the LANGUAGES setting from
829  
-    your setting file (or the default settings) and
830  
-    put it into the named variable.
831  
-    """
832  
-
833  
-    args = token.contents.split()
834  
-    if len(args) != 3 or args[1] != 'as':
835  
-        raise template.TemplateSyntaxError("'get_available_languages' requires 'as variable' (got %r)" % args)
836  
-    return GetAvailableLanguagesNode(args[2])
837  
-
838  
-def do_i18n(parser, token):
839  
-    """
840  
-    translate a given string with the current
841  
-    translation object.
842  
-
843  
-    For example::
844  
-
845  
-        {% i18n _('test') %}
846  
-        {% i18n ngettext('singular', 'plural', counter) %}
847  
-
848  
-    """
849  
-    args = token.contents.split(' ', 1)
850  
-    if len(args) != 2:
851  
-        raise template.TemplateSyntaxError("'i18n' requires one argument (got %r)" % args)
852  
-
853  
-    return I18NNode(args[1].strip())
854  
-
855 759
 register_tag('comment', do_comment)
856 760
 register_tag('cycle', do_cycle)
857 761
 register_tag('debug', do_debug)
@@ -868,5 +772,3 @@ def do_i18n(parser, token):
868 772
 register_tag('now', do_now)
869 773
 register_tag('templatetag', do_templatetag)
870 774
 register_tag('widthratio', do_widthratio)
871  
-register_tag('i18n', do_i18n)
872  
-register_tag('get_available_languages', do_get_available_languages)
33  django/templatetags/i18n.py
@@ -18,7 +18,7 @@ def render(self, context):
18 18
         context[self.variable] = LANGUAGES
19 19
         return ''
20 20
 
21  
-class GetCurrentLanguage(Node):
  21
+class GetCurrentLanguageNode(Node):
22 22
 
23 23
     def __init__(self, variable):
24 24
         self.variable = variable
@@ -112,7 +112,7 @@ def do_get_current_language(parser, token):
112 112
     args = token.contents.split()
113 113
     if len(args) != 3 or args[1] != 'as':
114 114
         raise TemplateSyntaxError, "'get_available_languages' requires 'as variable' (got %r)" % args
115  
-    return GetAvailableLanguagesNode(args[2])
  115
+    return GetCurrentLanguageNode(args[2])
116 116
 
117 117
 def do_translate(parser, token):
118 118
     """
@@ -144,14 +144,21 @@ def do_translate(parser, token):
144 144
     the variable ``variable``. Make sure that the string
145 145
     in there is something that is in the .po file.
146 146
     """
147  
-    args = token.contents.split(None, 1)
148  
-    p = args[1].rfind(' ')
149  
-    noop = False
150  
-    value = ''
151  
-    if p >= 0 and args[1][p:].strip() == 'noop':
152  
-        value = args[1][:p].strip()
153  
-    else:
154  
-        value = args[1]
  147
+
  148
+    class TranslateParser(TokenParser):
  149
+
  150
+        def top(self):
  151
+            value = self.value()
  152
+            if self.more():
  153
+                if self.tag() == 'noop':
  154
+                    noop = True
  155
+                else:
  156
+                    raise TemplateSyntaxError, "only option for 'trans' is 'noop'"
  157
+            else:
  158
+                noop = False
  159
+            return (value, noop)
  160
+
  161
+    (value, noop) = TranslateParser(token.contents).top()
155 162
     return TranslateNode(value, noop)
156 163
 
157 164
 def do_block_translate(parser, token):
@@ -189,7 +196,7 @@ def top(self):
189 196
             singular.append(token)
190 197
         else:
191 198
             break
192  
-    if countervar and counter:  
  199
+    if countervar and counter:
193 200
         if token.contents.strip() != 'plural':
194 201
             raise TemplateSyntaxError, "'blocktrans' doesn't allow other block tags inside it" % tag
195 202
         while parser.tokens:
@@ -200,11 +207,11 @@ def top(self):
200 207
                 break
201 208
     if token.contents.strip() != 'endblocktrans':
202 209
         raise TemplateSyntaxError, "'blocktrans' doesn't allow other block tags (seen %r) inside it" % token.contents
203  
-    
  210
+
204 211
     return BlockTranslateNode(extra_context, singular, plural, countervar, counter)
205 212
 
206 213
 register_tag('get_available_languages', do_get_available_languages)
207  
-register_tag('get_curent_language', do_get_current_language)
  214
+register_tag('get_current_language', do_get_current_language)
208 215
 register_tag('trans', do_translate)
209 216
 register_tag('blocktrans', do_block_translate)
210 217
 
35  tests/othertests/templates.py
@@ -218,49 +218,40 @@ def method(self):
218 218
     'exception04': ("{% extends 'inheritance17' %}{% block first %}{% echo 400 %}5678{% endblock %}", {}, template.TemplateSyntaxError),
219 219
 
220 220
     # simple translation of a string delimited by '
221  
-    'i18n01': ("{% i18n _('xxxyyyxxx') %}", {}, "xxxyyyxxx"),
  221
+    'i18n01': ("{% load i18n %}{% trans 'xxxyyyxxx' %}", {}, "xxxyyyxxx"),
222 222
 
223 223
     # simple translation of a string delimited by "
224  
-    'i18n02': ('{% i18n _("xxxyyyxxx") %}', {}, "xxxyyyxxx"),
225  
-
226  
-    # simple translation of a string delimited by """
227  
-    'i18n03': ('{% i18n _("""xxxyyyxxx""") %}', {}, "xxxyyyxxx"),
  224
+    'i18n02': ('{% load i18n %}{% trans "xxxyyyxxx" %}', {}, "xxxyyyxxx"),
228 225
 
229 226
     # simple translation of a variable
230  
-    'i18n04': ('{% i18n _(anton) %}', {'anton': 'xxxyyyxxx'}, "xxxyyyxxx"),
  227
+    'i18n03': ('{% load i18n %}{% blocktrans %}{{ anton }}{% endblocktrans %}', {'anton': 'xxxyyyxxx'}, "xxxyyyxxx"),
231 228
 
232  
-    # simple translation of a variable
233  
-    'i18n05': ('{% i18n _(anton|lower) %}', {'anton': 'XXXYYYXXX'}, "xxxyyyxxx"),
  229
+    # simple translation of a variable and filter
  230
+    'i18n04': ('{% load i18n %}{% blocktrans with anton|lower as berta %}{{ berta }}{% endblocktrans %}', {'anton': 'XXXYYYXXX'}, "xxxyyyxxx"),
234 231
 
235 232
     # simple translation of a string with interpolation
236  
-    'i18n05': ('{% i18n _("xxx%(anton)sxxx") %}', {'anton': 'yyy'}, "xxxyyyxxx"),
  233
+    'i18n05': ('{% load i18n %}{% blocktrans %}xxx{{ anton }}xxx{% endblocktrans %}', {'anton': 'yyy'}, "xxxyyyxxx"),
237 234
 
238 235
     # simple translation of a string to german
239  
-    'i18n07': ('{% i18n _("Page not found") %}', {'LANGUAGE_CODE': 'de'}, "Seite nicht gefunden"),
  236
+    'i18n06': ('{% load i18n %}{% trans "Page not found" %}', {'LANGUAGE_CODE': 'de'}, "Seite nicht gefunden"),
240 237
 
241 238
     # translation of singular form
242  
-    'i18n08': ('{% i18n ngettext("singular", "plural", count) %}', {'count': 1}, "singular"),
  239
+    'i18n07': ('{% load i18n %}{% blocktrans count number as counter %}singular{% plural %}plural{% endblocktrans %}', {'number': 1}, "singular"),
243 240
 
244 241
     # translation of plural form
245  
-    'i18n09': ('{% i18n ngettext("singular", "plural", count) %}', {'count': 2}, "plural"),
  242
+    'i18n08': ('{% load i18n %}{% blocktrans count number as counter %}singular{% plural %}plural{% endblocktrans %}', {'number': 2}, "plural"),
246 243
 
247 244
     # simple non-translation (only marking) of a string to german
248  
-    'i18n10': ('{% i18n gettext_noop("Page not found") %}', {'LANGUAGE_CODE': 'de'}, "Page not found"),
249  
-
250  
-    # translation of string without i18n tag
251  
-    'i18n11': ('{{ _("blah") }}', {}, "blah"),
252  
-
253  
-    # translation of string without i18n tag but with interpolation
254  
-    'i18n12': ('{{ _("blah%(anton)s") }}', {'anton': 'blubb'}, "blahblubb"),
  245
+    'i18n09': ('{% load i18n %}{% trans "Page not found" noop %}', {'LANGUAGE_CODE': 'de'}, "Page not found"),
255 246
 
256 247
     # translation of a variable with a translated filter
257  
-    'i18n13': ('{{ bool|yesno:_("ja,nein") }}', {'bool': True}, 'ja'),
  248
+    'i18n10': ('{{ bool|yesno:_("ja,nein") }}', {'bool': True}, 'ja'),
258 249
 
259 250
     # translation of a variable with a non-translated filter
260  
-    'i18n14': ('{{ bool|yesno:"ja,nein" }}', {'bool': True}, 'ja'),
  251
+    'i18n11': ('{{ bool|yesno:"ja,nein" }}', {'bool': True}, 'ja'),
261 252
 
262 253
     # usage of the get_available_languages tag
263  
-    'i18n15': ('{% get_available_languages as langs %}{% for lang in langs %}{% ifequal lang.0 "de" %}{{ lang.0 }}{% endifequal %}{% endfor %}', {}, 'de'),
  254
+    'i18n12': ('{% load i18n %}{% get_available_languages as langs %}{% for lang in langs %}{% ifequal lang.0 "de" %}{{ lang.0 }}{% endifequal %}{% endfor %}', {}, 'de'),
264 255
 }
265 256
 
266 257
 def test_template_loader(template_name, template_dirs=None):

0 notes on commit 1470bb0

Please sign in to comment.
Something went wrong with that request. Please try again.