Skip to content
Myr

[svn] added support for translations (unstable api)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

--HG-- branch : trunk

authored by Armin Ronacher · committed by Armin Ronacher · parent 0a1742e · Browse files · 7 files+208 added−16 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

7 files+208 added−16 removed

  • other:+208 added−16 removed

7 files+208 added−16 removed

modified:jinja/translators/python.py+40 added-8 removed
9 unmodified lines
10"""11from compiler import ast12from jinja import nodes13from jinja.parser import Parser14from jinja.datastructure import Context14from jinja.exceptions import TemplateSyntaxError15from jinja.translators import Translator1617
35 unmodified lines
53 ns = {}54 exec self.code in ns55 self.generate_func = ns['generate']56 result = []58 ctx = Context(self.environment, *args, **kwargs)57 ctx = self.environment.context_class(self.environment, *args, **kwargs)58 self.generate_func(ctx, result.append)59 return u''.join(result)6061
26 unmodified lines
88 nodes.Set: self.handle_set,89 nodes.Filter: self.handle_filter,90 nodes.Block: self.handle_block,91 nodes.Include: self.handle_include,92 nodes.Trans: self.handle_trans,93 # used python nodes94 ast.Name: self.handle_name,95 ast.AssName: self.handle_name,96 ast.Compare: self.handle_compare,
30 unmodified lines
127 self.unsupported.update({128 ast.GenExpr: 'generator expressions'129 })130131 self.require_translations = False132133 # -- public methods134135 def process(environment, node):136 translator = PythonTranslator(environment, node)
83 unmodified lines
220 lines = [221 'from __future__ import division\n'222 'from jinja.datastructure import Undefined, LoopContext, CycleContext\n\n'223 'def generate(context, write):\n'222 ' # BOOTSTRAPPING CODE\n'224 ' environment = context.environment\n'225 ' get_attribute = environment.get_attribute\n'226 ' perform_test = environment.perform_test\n'227 ' apply_filters = environment.apply_filters\n'228 ' call_function = environment.call_function\n'229 ' call_function_simple = environment.call_function_simple\n'229 ' finish_var = environment.finish_var\n\n'230 ' # TEMPLATE CODE'230 ' finish_var = environment.finish_var\n'231 ]232 self.indention += 1233 lines.append(self.handle_node_list(node))234 self.indention -= 1232 self.indention = 1233 rv = self.handle_node_list(node)234235 if self.require_translations:236 lines.append(' translate = context.get_translator()')237 lines.append(rv)238239 return '\n'.join(lines)240241 def handle_template_text(self, node):242 """
201 unmodified lines
444 buf.append(self.handle_node(tmpl))445 buf.append(self.indent('# END OF INCLUSION'))446 return '\n'.join(buf)447448 def handle_trans(self, node):449 """450 Handle translations.451 """452 self.require_translations = True453 if node.replacements:454 replacements = []455 for name, n in node.replacements.iteritems():456 replacements.append('%r: %s' % (457 name,458 self.handle_node(n)459 ))460 replacements = '{%s}' % ', '.join(replacements)461 else:462 replacements = 'None'463 if node.indicator is not None:464 indicator = 'context[\'%s\']' % node.indicator465 else:466 indicator = 'None'467 return self.indent('write(translate(%r, %r, %s) %% %s)' % (468 node.singular,469 node.plural,470 indicator,471 replacements472 ))473474 # -- python nodes475476 def handle_name(self, node):477 """478 Handle name assignments and name retreivement.479 """480 if node.name in self.constants:481 return self.constants[node.name]482 elif node.name == '_':483 self.require_translations = True484 return 'translate'485 return 'context[%r]' % node.name486487 def handle_compare(self, node):488 """
264 unmodified lines
modified:jinja/datastructure.py+4 added-3 removed
110 unmodified lines
111112 # cache object used for filters and tests113 self.cache = {}114115 def get_translator(self):116 """Return the translator for i18n."""117 return lambda a, b, c: a118119 def pop(self):120 if len(self._stack) <= 2:121 raise ValueError('cannot pop initial layer')122 rv = self._stack.pop()
97 unmodified lines
220 if self.loop_function is not None:221 return self.loop_function(seq)222 return Undefined223220 def __repr__(self):221 return str(self._stack)224223225class CycleContext(object):226 """227 Helper class used for cycling.228 """
77 unmodified lines
modified:jinja/environment.py+4 added-2 removed
10 unmodified lines
11import re12from jinja.lexer import Lexer13from jinja.parser import Parser14from jinja.loaders import LoaderWrapper15from jinja.datastructure import Undefined15from jinja.datastructure import Undefined, Context16from jinja.utils import escape17from jinja.exceptions import FilterNotFound, TestNotFound, SecurityException18from jinja.defaults import DEFAULT_FILTERS, DEFAULT_TESTS, DEFAULT_NAMESPACE19
16 unmodified lines
36 charset='utf-8',37 namespace=None,38 loader=None,39 filters=None,40 tests=None):40 tests=None,41 context_class=Context):4243 # lexer / parser information44 self.block_start_string = block_start_string45 self.block_end_string = block_end_string
9 unmodified lines
55 self.loader = loader56 self.filters = filters is None and DEFAULT_FILTERS.copy() or filters57 self.tests = tests is None and DEFAULT_TESTS.copy() or tests58 self.auto_escape = auto_escape59 self.context_class = context_class6061 # global namespace62 self.globals = namespace is None and DEFAULT_NAMESPACE.copy() \63 or namespace or {}
117 unmodified lines
modified:jinja/loaders.py+3 added
66 unmodified lines
67 """Helper method that overrides all other methods if no68 loader is defined."""69 raise RuntimeError('no loader defined')7071 def __nonzero__(self):72 return self.loader is not None737475class FileSystemLoader(object):76 """77 Loads templates from the filesystem:78
54 unmodified lines
modified:jinja/nodes.py+28 added
298 unmodified lines
299 return [self.template]300301 def __repr__(self):302 return 'Include(%r)' % self.template303304305class Trans(Node):306 """307 A node for translatable sections.308 """309310 def __init__(self, lineno, singular, plural, indicator, replacements):311 self.lineno = lineno312 self.singular = singular313 self.plural = plural314 self.indicator = indicator315 self.replacements = replacements316317 def get_items(self):318 rv = [self.singular, self.plural, self.indicator]319 if self.replacements:320 rv.extend(self.replacements.values())321 rv.extend(self.replacements.keys())322 return rv323324 def __repr__(self):325 return 'Trans(%r, %r, %r, %r)' % (326 self.singular,327 self.plural,328 self.indicator,329 self.replacements330 )
modified:jinja/parser.py+127 added-2 removed
24 unmodified lines
25end_of_if = lambda p, t, d: t == 'name' and d == 'endif'26end_of_filter = lambda p, t, d: t == 'name' and d == 'endfilter'27end_of_macro = lambda p, t, d: t == 'name' and d == 'endmacro'28end_of_block_tag = lambda p, t, d: t == 'name' and d == 'endblock'29end_of_raw = lambda p, t, d: t == 'name' and d == 'endraw'29end_of_trans = lambda p, t, d: t == 'name' and d == 'endtrans'303132string_inc_re = re.compile(r'(?:[^\d]*(\d+)[^\d]*)+')333435def inc_string(s):36 """37 Increment a string38 """39 m = string_inc_re.search(s)40 if m:41 next = str(int(m.group(1)) + 1)42 start, end = m.span(1)43 s = s[:max(end - len(next), start)] + next + s[end:]44 else:45 name, ext = s.rsplit('.', 1)46 return '%s2.%s' % (name, ext)47 return s484950class Parser(object):51 """52 The template parser class.53
20 unmodified lines
74 'print': self.handle_print_directive,75 'macro': self.handle_macro_directive,76 'block': self.handle_block_directive,77 'extends': self.handle_extends_directive,60 'include': self.handle_include_directive78 'include': self.handle_include_directive,79 'trans': self.handle_trans_directive80 }8182 def handle_for_directive(self, lineno, gen):83 """
165 unmodified lines
249 if len(tokens) != 1 or tokens[0][1] != 'string':250 raise TemplateSyntaxError('include requires a string', lineno)251 return nodes.Include(lineno, tokens[0][2][1:-1])252253 def handle_trans_directive(self, lineno, gen):254 """255 Handle translatable sections.256 """257 # save the initial line number for the resulting node258 flineno = lineno259 try:260 # check for string translations261 lineno, token, data = gen.next()262 if token == 'string':263 # check that there are not any more elements264 try:265 gen.next()266 except StopIteration:267 #XXX: what about escapes?268 return nodes.Trans(lineno, data[1:-1], None, None, None)269 raise TemplateSyntaxError('string based translations '270 'require at most one argument.',271 lineno)272273 # create a new generator with the popped item as first one274 def wrapgen(oldgen):275 yield lineno, token, data276 for item in oldgen:277 yield item278 gen = wrapgen(gen)279280 # block based translations281 first_var = None282 replacements = {}283 for arg in self.parse_python(lineno, gen, '_trans(%s)').expr.args:284 if arg.__class__ is not ast.Keyword:285 raise TemplateSyntaxError('translation tags need explicit '286 'names for values.', lineno)287 if first_var is None:288 first_var = arg.name289 replacements[arg.name] = arg.expr290291 # look for endtrans/pluralize292 buf = singular = []293 plural = indicator = None294295 while True:296 lineno, token, data = self.tokenstream.next()297 # nested variables298 if token == 'variable_begin':299 _, variable_token, variable_name = self.tokenstream.next()300 if variable_token != 'name' or variable_name not in replacements:301 raise TemplateSyntaxError('unregistered translation '302 'variable %r.' % variable_name,303 lineno)304 if self.tokenstream.next()[1] != 'variable_end':305 raise TemplateSyntaxError('invalid syntax for variable '306 'expression.', lineno)307 buf.append('%%(%s)s' % variable_name)308 # nested blocks are not supported, just look for end blocks309 elif token == 'block_begin':310 _, block_token, block_name = self.tokenstream.next()311 if block_token != 'name' or \312 block_name not in ('pluralize', 'endtrans'):313 raise TemplateSyntaxError('blocks in translatable sections '314 'are not supported', lineno)315 # pluralize316 if block_name == 'pluralize':317 if plural is not None:318 raise TemplateSyntaxError('translation blocks support '319 'at most one plural block',320 lineno)321 _, plural_token, plural_name = self.tokenstream.next()322 if plural_token == 'block_end':323 indicator = first_var324 elif plural_token == 'name':325 if plural_name not in replacements:326 raise TemplateSyntaxError('unknown tranlsation '327 'variable %r' %328 plural_name, lineno)329 elif self.tokenstream.next()[1] != 'block_end':330 raise TemplateSyntaxError('pluralize takes '331 'at most one '332 'argument', lineno)333 indicator = plural_name334 else:335 raise TemplateSyntaxError('pluralize requires no '336 'argument or a variable '337 'name.')338 plural = buf = []339 # end translation340 elif block_name == 'endtrans':341 self.close_remaining_block()342 break343 # normal data344 else:345 if replacements:346 data = data.replace('%', '%%')347 buf.append(data)348349 except StopIteration:350 raise TemplateSyntaxError('unexpected end of translation section',351 self.tokenstream.last[0])352353 singular = u''.join(singular)354 if plural is not None:355 plural = u''.join(plural)356 return nodes.Trans(flineno, singular, plural, indicator, replacements or None)357358359 def parse_python(self, lineno, gen, template):360 """361 Convert the passed generator into a flat string representing362 python sourcecode and return an ast node or raise a
115 unmodified lines
modified:www/static/style.css+2 added-1 removed