You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

i18n.py 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. from django.conf import settings
  2. from django.template import Library, Node, TemplateSyntaxError, Variable
  3. from django.template.base import TokenType, render_value_in_context
  4. from django.template.defaulttags import token_kwargs
  5. from django.utils import translation
  6. from django.utils.safestring import SafeData, mark_safe
  7. register = Library()
  8. class GetAvailableLanguagesNode(Node):
  9. def __init__(self, variable):
  10. self.variable = variable
  11. def render(self, context):
  12. context[self.variable] = [(k, translation.gettext(v)) for k, v in settings.LANGUAGES]
  13. return ''
  14. class GetLanguageInfoNode(Node):
  15. def __init__(self, lang_code, variable):
  16. self.lang_code = lang_code
  17. self.variable = variable
  18. def render(self, context):
  19. lang_code = self.lang_code.resolve(context)
  20. context[self.variable] = translation.get_language_info(lang_code)
  21. return ''
  22. class GetLanguageInfoListNode(Node):
  23. def __init__(self, languages, variable):
  24. self.languages = languages
  25. self.variable = variable
  26. def get_language_info(self, language):
  27. # ``language`` is either a language code string or a sequence
  28. # with the language code as its first item
  29. if len(language[0]) > 1:
  30. return translation.get_language_info(language[0])
  31. else:
  32. return translation.get_language_info(str(language))
  33. def render(self, context):
  34. langs = self.languages.resolve(context)
  35. context[self.variable] = [self.get_language_info(lang) for lang in langs]
  36. return ''
  37. class GetCurrentLanguageNode(Node):
  38. def __init__(self, variable):
  39. self.variable = variable
  40. def render(self, context):
  41. context[self.variable] = translation.get_language()
  42. return ''
  43. class GetCurrentLanguageBidiNode(Node):
  44. def __init__(self, variable):
  45. self.variable = variable
  46. def render(self, context):
  47. context[self.variable] = translation.get_language_bidi()
  48. return ''
  49. class TranslateNode(Node):
  50. def __init__(self, filter_expression, noop, asvar=None,
  51. message_context=None):
  52. self.noop = noop
  53. self.asvar = asvar
  54. self.message_context = message_context
  55. self.filter_expression = filter_expression
  56. if isinstance(self.filter_expression.var, str):
  57. self.filter_expression.var = Variable("'%s'" %
  58. self.filter_expression.var)
  59. def render(self, context):
  60. self.filter_expression.var.translate = not self.noop
  61. if self.message_context:
  62. self.filter_expression.var.message_context = (
  63. self.message_context.resolve(context))
  64. output = self.filter_expression.resolve(context)
  65. value = render_value_in_context(output, context)
  66. # Restore percent signs. Percent signs in template text are doubled
  67. # so they are not interpreted as string format flags.
  68. is_safe = isinstance(value, SafeData)
  69. value = value.replace('%%', '%')
  70. value = mark_safe(value) if is_safe else value
  71. if self.asvar:
  72. context[self.asvar] = value
  73. return ''
  74. else:
  75. return value
  76. class BlockTranslateNode(Node):
  77. def __init__(self, extra_context, singular, plural=None, countervar=None,
  78. counter=None, message_context=None, trimmed=False, asvar=None):
  79. self.extra_context = extra_context
  80. self.singular = singular
  81. self.plural = plural
  82. self.countervar = countervar
  83. self.counter = counter
  84. self.message_context = message_context
  85. self.trimmed = trimmed
  86. self.asvar = asvar
  87. def render_token_list(self, tokens):
  88. result = []
  89. vars = []
  90. for token in tokens:
  91. if token.token_type == TokenType.TEXT:
  92. result.append(token.contents.replace('%', '%%'))
  93. elif token.token_type == TokenType.VAR:
  94. result.append('%%(%s)s' % token.contents)
  95. vars.append(token.contents)
  96. msg = ''.join(result)
  97. if self.trimmed:
  98. msg = translation.trim_whitespace(msg)
  99. return msg, vars
  100. def render(self, context, nested=False):
  101. if self.message_context:
  102. message_context = self.message_context.resolve(context)
  103. else:
  104. message_context = None
  105. # Update() works like a push(), so corresponding context.pop() is at
  106. # the end of function
  107. context.update({var: val.resolve(context) for var, val in self.extra_context.items()})
  108. singular, vars = self.render_token_list(self.singular)
  109. if self.plural and self.countervar and self.counter:
  110. count = self.counter.resolve(context)
  111. context[self.countervar] = count
  112. plural, plural_vars = self.render_token_list(self.plural)
  113. if message_context:
  114. result = translation.npgettext(message_context, singular,
  115. plural, count)
  116. else:
  117. result = translation.ngettext(singular, plural, count)
  118. vars.extend(plural_vars)
  119. else:
  120. if message_context:
  121. result = translation.pgettext(message_context, singular)
  122. else:
  123. result = translation.gettext(singular)
  124. default_value = context.template.engine.string_if_invalid
  125. def render_value(key):
  126. if key in context:
  127. val = context[key]
  128. else:
  129. val = default_value % key if '%s' in default_value else default_value
  130. return render_value_in_context(val, context)
  131. data = {v: render_value(v) for v in vars}
  132. context.pop()
  133. try:
  134. result = result % data
  135. except (KeyError, ValueError):
  136. if nested:
  137. # Either string is malformed, or it's a bug
  138. raise TemplateSyntaxError(
  139. "'blocktrans' is unable to format string returned by gettext: %r using %r"
  140. % (result, data)
  141. )
  142. with translation.override(None):
  143. result = self.render(context, nested=True)
  144. if self.asvar:
  145. context[self.asvar] = result
  146. return ''
  147. else:
  148. return result
  149. class LanguageNode(Node):
  150. def __init__(self, nodelist, language):
  151. self.nodelist = nodelist
  152. self.language = language
  153. def render(self, context):
  154. with translation.override(self.language.resolve(context)):
  155. output = self.nodelist.render(context)
  156. return output
  157. @register.tag("get_available_languages")
  158. def do_get_available_languages(parser, token):
  159. """
  160. Store a list of available languages in the context.
  161. Usage::
  162. {% get_available_languages as languages %}
  163. {% for language in languages %}
  164. ...
  165. {% endfor %}
  166. This puts settings.LANGUAGES into the named variable.
  167. """
  168. # token.split_contents() isn't useful here because this tag doesn't accept variable as arguments
  169. args = token.contents.split()
  170. if len(args) != 3 or args[1] != 'as':
  171. raise TemplateSyntaxError("'get_available_languages' requires 'as variable' (got %r)" % args)
  172. return GetAvailableLanguagesNode(args[2])
  173. @register.tag("get_language_info")
  174. def do_get_language_info(parser, token):
  175. """
  176. Store the language information dictionary for the given language code in a
  177. context variable.
  178. Usage::
  179. {% get_language_info for LANGUAGE_CODE as l %}
  180. {{ l.code }}
  181. {{ l.name }}
  182. {{ l.name_translated }}
  183. {{ l.name_local }}
  184. {{ l.bidi|yesno:"bi-directional,uni-directional" }}
  185. """
  186. args = token.split_contents()
  187. if len(args) != 5 or args[1] != 'for' or args[3] != 'as':
  188. raise TemplateSyntaxError("'%s' requires 'for string as variable' (got %r)" % (args[0], args[1:]))
  189. return GetLanguageInfoNode(parser.compile_filter(args[2]), args[4])
  190. @register.tag("get_language_info_list")
  191. def do_get_language_info_list(parser, token):
  192. """
  193. Store a list of language information dictionaries for the given language
  194. codes in a context variable. The language codes can be specified either as
  195. a list of strings or a settings.LANGUAGES style list (or any sequence of
  196. sequences whose first items are language codes).
  197. Usage::
  198. {% get_language_info_list for LANGUAGES as langs %}
  199. {% for l in langs %}
  200. {{ l.code }}
  201. {{ l.name }}
  202. {{ l.name_translated }}
  203. {{ l.name_local }}
  204. {{ l.bidi|yesno:"bi-directional,uni-directional" }}
  205. {% endfor %}
  206. """
  207. args = token.split_contents()
  208. if len(args) != 5 or args[1] != 'for' or args[3] != 'as':
  209. raise TemplateSyntaxError("'%s' requires 'for sequence as variable' (got %r)" % (args[0], args[1:]))
  210. return GetLanguageInfoListNode(parser.compile_filter(args[2]), args[4])
  211. @register.filter
  212. def language_name(lang_code):
  213. return translation.get_language_info(lang_code)['name']
  214. @register.filter
  215. def language_name_translated(lang_code):
  216. english_name = translation.get_language_info(lang_code)['name']
  217. return translation.gettext(english_name)
  218. @register.filter
  219. def language_name_local(lang_code):
  220. return translation.get_language_info(lang_code)['name_local']
  221. @register.filter
  222. def language_bidi(lang_code):
  223. return translation.get_language_info(lang_code)['bidi']
  224. @register.tag("get_current_language")
  225. def do_get_current_language(parser, token):
  226. """
  227. Store the current language in the context.
  228. Usage::
  229. {% get_current_language as language %}
  230. This fetches the currently active language and puts its value into the
  231. ``language`` context variable.
  232. """
  233. # token.split_contents() isn't useful here because this tag doesn't accept variable as arguments
  234. args = token.contents.split()
  235. if len(args) != 3 or args[1] != 'as':
  236. raise TemplateSyntaxError("'get_current_language' requires 'as variable' (got %r)" % args)
  237. return GetCurrentLanguageNode(args[2])
  238. @register.tag("get_current_language_bidi")
  239. def do_get_current_language_bidi(parser, token):
  240. """
  241. Store the current language layout in the context.
  242. Usage::
  243. {% get_current_language_bidi as bidi %}
  244. This fetches the currently active language's layout and puts its value into
  245. the ``bidi`` context variable. True indicates right-to-left layout,
  246. otherwise left-to-right.
  247. """
  248. # token.split_contents() isn't useful here because this tag doesn't accept variable as arguments
  249. args = token.contents.split()
  250. if len(args) != 3 or args[1] != 'as':
  251. raise TemplateSyntaxError("'get_current_language_bidi' requires 'as variable' (got %r)" % args)
  252. return GetCurrentLanguageBidiNode(args[2])
  253. @register.tag("trans")
  254. def do_translate(parser, token):
  255. """
  256. Mark a string for translation and translate the string for the current
  257. language.
  258. Usage::
  259. {% trans "this is a test" %}
  260. This marks the string for translation so it will be pulled out by
  261. makemessages into the .po files and runs the string through the translation
  262. engine.
  263. There is a second form::
  264. {% trans "this is a test" noop %}
  265. This marks the string for translation, but returns the string unchanged.
  266. Use it when you need to store values into forms that should be translated
  267. later on.
  268. You can use variables instead of constant strings
  269. to translate stuff you marked somewhere else::
  270. {% trans variable %}
  271. This tries to translate the contents of the variable ``variable``. Make
  272. sure that the string in there is something that is in the .po file.
  273. It is possible to store the translated string into a variable::
  274. {% trans "this is a test" as var %}
  275. {{ var }}
  276. Contextual translations are also supported::
  277. {% trans "this is a test" context "greeting" %}
  278. This is equivalent to calling pgettext instead of (u)gettext.
  279. """
  280. bits = token.split_contents()
  281. if len(bits) < 2:
  282. raise TemplateSyntaxError("'%s' takes at least one argument" % bits[0])
  283. message_string = parser.compile_filter(bits[1])
  284. remaining = bits[2:]
  285. noop = False
  286. asvar = None
  287. message_context = None
  288. seen = set()
  289. invalid_context = {'as', 'noop'}
  290. while remaining:
  291. option = remaining.pop(0)
  292. if option in seen:
  293. raise TemplateSyntaxError(
  294. "The '%s' option was specified more than once." % option,
  295. )
  296. elif option == 'noop':
  297. noop = True
  298. elif option == 'context':
  299. try:
  300. value = remaining.pop(0)
  301. except IndexError:
  302. raise TemplateSyntaxError(
  303. "No argument provided to the '%s' tag for the context option." % bits[0]
  304. )
  305. if value in invalid_context:
  306. raise TemplateSyntaxError(
  307. "Invalid argument '%s' provided to the '%s' tag for the context option" % (value, bits[0]),
  308. )
  309. message_context = parser.compile_filter(value)
  310. elif option == 'as':
  311. try:
  312. value = remaining.pop(0)
  313. except IndexError:
  314. raise TemplateSyntaxError(
  315. "No argument provided to the '%s' tag for the as option." % bits[0]
  316. )
  317. asvar = value
  318. else:
  319. raise TemplateSyntaxError(
  320. "Unknown argument for '%s' tag: '%s'. The only options "
  321. "available are 'noop', 'context' \"xxx\", and 'as VAR'." % (
  322. bits[0], option,
  323. )
  324. )
  325. seen.add(option)
  326. return TranslateNode(message_string, noop, asvar, message_context)
  327. @register.tag("blocktrans")
  328. def do_block_translate(parser, token):
  329. """
  330. Translate a block of text with parameters.
  331. Usage::
  332. {% blocktrans with bar=foo|filter boo=baz|filter %}
  333. This is {{ bar }} and {{ boo }}.
  334. {% endblocktrans %}
  335. Additionally, this supports pluralization::
  336. {% blocktrans count count=var|length %}
  337. There is {{ count }} object.
  338. {% plural %}
  339. There are {{ count }} objects.
  340. {% endblocktrans %}
  341. This is much like ngettext, only in template syntax.
  342. The "var as value" legacy format is still supported::
  343. {% blocktrans with foo|filter as bar and baz|filter as boo %}
  344. {% blocktrans count var|length as count %}
  345. The translated string can be stored in a variable using `asvar`::
  346. {% blocktrans with bar=foo|filter boo=baz|filter asvar var %}
  347. This is {{ bar }} and {{ boo }}.
  348. {% endblocktrans %}
  349. {{ var }}
  350. Contextual translations are supported::
  351. {% blocktrans with bar=foo|filter context "greeting" %}
  352. This is {{ bar }}.
  353. {% endblocktrans %}
  354. This is equivalent to calling pgettext/npgettext instead of
  355. (u)gettext/(u)ngettext.
  356. """
  357. bits = token.split_contents()
  358. options = {}
  359. remaining_bits = bits[1:]
  360. asvar = None
  361. while remaining_bits:
  362. option = remaining_bits.pop(0)
  363. if option in options:
  364. raise TemplateSyntaxError('The %r option was specified more '
  365. 'than once.' % option)
  366. if option == 'with':
  367. value = token_kwargs(remaining_bits, parser, support_legacy=True)
  368. if not value:
  369. raise TemplateSyntaxError('"with" in %r tag needs at least '
  370. 'one keyword argument.' % bits[0])
  371. elif option == 'count':
  372. value = token_kwargs(remaining_bits, parser, support_legacy=True)
  373. if len(value) != 1:
  374. raise TemplateSyntaxError('"count" in %r tag expected exactly '
  375. 'one keyword argument.' % bits[0])
  376. elif option == "context":
  377. try:
  378. value = remaining_bits.pop(0)
  379. value = parser.compile_filter(value)
  380. except Exception:
  381. raise TemplateSyntaxError(
  382. '"context" in %r tag expected exactly one argument.' % bits[0]
  383. )
  384. elif option == "trimmed":
  385. value = True
  386. elif option == "asvar":
  387. try:
  388. value = remaining_bits.pop(0)
  389. except IndexError:
  390. raise TemplateSyntaxError(
  391. "No argument provided to the '%s' tag for the asvar option." % bits[0]
  392. )
  393. asvar = value
  394. else:
  395. raise TemplateSyntaxError('Unknown argument for %r tag: %r.' %
  396. (bits[0], option))
  397. options[option] = value
  398. if 'count' in options:
  399. countervar, counter = next(iter(options['count'].items()))
  400. else:
  401. countervar, counter = None, None
  402. if 'context' in options:
  403. message_context = options['context']
  404. else:
  405. message_context = None
  406. extra_context = options.get('with', {})
  407. trimmed = options.get("trimmed", False)
  408. singular = []
  409. plural = []
  410. while parser.tokens:
  411. token = parser.next_token()
  412. if token.token_type in (TokenType.VAR, TokenType.TEXT):
  413. singular.append(token)
  414. else:
  415. break
  416. if countervar and counter:
  417. if token.contents.strip() != 'plural':
  418. raise TemplateSyntaxError("'blocktrans' doesn't allow other block tags inside it")
  419. while parser.tokens:
  420. token = parser.next_token()
  421. if token.token_type in (TokenType.VAR, TokenType.TEXT):
  422. plural.append(token)
  423. else:
  424. break
  425. if token.contents.strip() != 'endblocktrans':
  426. raise TemplateSyntaxError("'blocktrans' doesn't allow other block tags (seen %r) inside it" % token.contents)
  427. return BlockTranslateNode(extra_context, singular, plural, countervar,
  428. counter, message_context, trimmed=trimmed,
  429. asvar=asvar)
  430. @register.tag
  431. def language(parser, token):
  432. """
  433. Enable the given language just for this block.
  434. Usage::
  435. {% language "de" %}
  436. This is {{ bar }} and {{ boo }}.
  437. {% endlanguage %}
  438. """
  439. bits = token.split_contents()
  440. if len(bits) != 2:
  441. raise TemplateSyntaxError("'%s' takes one argument (language)" % bits[0])
  442. language = parser.compile_filter(bits[1])
  443. nodelist = parser.parse(('endlanguage',))
  444. parser.delete_first_token()
  445. return LanguageNode(nodelist, language)