Code

Ticket #5972: trans_understands_filter_alternate_version.2.diff

File trans_understands_filter_alternate_version.2.diff, 2.2 KB (added by Dmitri Fedortchenko <zeraien@…>, 6 years ago)

the backwards compatiblity fix in the previous patch was a little weak. This one does the trick a little better.

Line 
1Index: django/templatetags/i18n.py
2===================================================================
3--- django/templatetags/i18n.py (revision 6689)
4+++ django/templatetags/i18n.py (working copy)
5@@ -34,16 +34,18 @@
6         return ''
7 
8 class TranslateNode(Node):
9-    def __init__(self, value, noop):
10-        self.value = Variable(value)
11+    def __init__(self, filter_expression, noop):
12+        self.filter_expression = filter_expression
13         self.noop = noop
14 
15     def render(self, context):
16-        value = self.value.resolve(context)
17-        if self.noop:
18-            return value
19-        else:
20-            return translation.ugettext(value)
21+               
22+        if not self.noop:
23+            filter_expression = self.filter_expression.var.resolve(context)
24+            translated = translation.ugettext(filter_expression)
25+            self.filter_expression.var = Variable('"'+translated+'"')
26+        # Filters are applied here, since this is a FilterExpression
27+        return self.filter_expression.resolve(context)
28 
29 class BlockTranslateNode(Node):
30     def __init__(self, extra_context, singular, plural=None, countervar=None,
31@@ -171,6 +173,20 @@
32     class TranslateParser(TokenParser):
33         def top(self):
34             value = self.value()
35+
36+            # Backwards Compatiblity fix:
37+            # FilterExpression does not support single-quoted strings,
38+            # so we make a cheap localized fix in order to maintain
39+            # backwards compatibility with existing uses of ``trans``
40+            # where single quote use is supported.
41+            if value[0] == "'":
42+                pos = None
43+                m = re.match("^'([^']+)'(\|.*$)",value)
44+                if m:
45+                    value = '"%s"%s' % (m.group(1),m.group(2))
46+                elif value[-1] == "'":
47+                    value = '"%s"' % value[1:-1]
48+               
49             if self.more():
50                 if self.tag() == 'noop':
51                     noop = True
52@@ -180,7 +196,7 @@
53                 noop = False
54             return (value, noop)
55     value, noop = TranslateParser(token.contents).top()
56-    return TranslateNode(value, noop)
57+    return TranslateNode(parser.compile_filter(value), noop)
58 
59 def do_block_translate(parser, token):
60     """