Development of an internal social media platform with personalised dashboards for students
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

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