This extension adds gettext support to Jinja2.
| 156 | |
| 157 | |
| 158 | class InternationalizationExtension(Extension): |
| 159 | """This extension adds gettext support to Jinja2.""" |
| 160 | tags = set(['trans']) |
| 161 | |
| 162 | # TODO: the i18n extension is currently reevaluating values in a few |
| 163 | # situations. Take this example: |
| 164 | # {% trans count=something() %}{{ count }} foo{% pluralize |
| 165 | # %}{{ count }} fooss{% endtrans %} |
| 166 | # something is called twice here. One time for the gettext value and |
| 167 | # the other time for the n-parameter of the ngettext function. |
| 168 | |
| 169 | def __init__(self, environment): |
| 170 | Extension.__init__(self, environment) |
| 171 | environment.globals['_'] = _gettext_alias |
| 172 | environment.extend( |
| 173 | install_gettext_translations=self._install, |
| 174 | install_null_translations=self._install_null, |
| 175 | install_gettext_callables=self._install_callables, |
| 176 | uninstall_gettext_translations=self._uninstall, |
| 177 | extract_translations=self._extract, |
| 178 | newstyle_gettext=False |
| 179 | ) |
| 180 | |
| 181 | def _install(self, translations, newstyle=None): |
| 182 | gettext = getattr(translations, 'ugettext', None) |
| 183 | if gettext is None: |
| 184 | gettext = translations.gettext |
| 185 | ngettext = getattr(translations, 'ungettext', None) |
| 186 | if ngettext is None: |
| 187 | ngettext = translations.ngettext |
| 188 | self._install_callables(gettext, ngettext, newstyle) |
| 189 | |
| 190 | def _install_null(self, newstyle=None): |
| 191 | self._install_callables( |
| 192 | lambda x: x, |
| 193 | lambda s, p, n: (n != 1 and (p,) or (s,))[0], |
| 194 | newstyle |
| 195 | ) |
| 196 | |
| 197 | def _install_callables(self, gettext, ngettext, newstyle=None): |
| 198 | if newstyle is not None: |
| 199 | self.environment.newstyle_gettext = newstyle |
| 200 | if self.environment.newstyle_gettext: |
| 201 | gettext = _make_new_gettext(gettext) |
| 202 | ngettext = _make_new_ngettext(ngettext) |
| 203 | self.environment.globals.update( |
| 204 | gettext=gettext, |
| 205 | ngettext=ngettext |
| 206 | ) |
| 207 | |
| 208 | def _uninstall(self, translations): |
| 209 | for key in 'gettext', 'ngettext': |
| 210 | self.environment.globals.pop(key, None) |
| 211 | |
| 212 | def _extract(self, source, gettext_functions=GETTEXT_FUNCTIONS): |
| 213 | if isinstance(source, string_types): |
| 214 | source = self.environment.parse(source) |
| 215 | return extract_from_ast(source, gettext_functions) |
nothing calls this directly
no test coverage detected
searching dependent graphs…