| 862 | Using translations outside views and templates |
| 863 | ============================================== |
| 864 | |
| 865 | While Django provides rich set of i18n tools for use in views and templates, |
| 866 | it does not restrict the usage to Django-specific code. The Django translation |
| 867 | mechanisms can be used to translate arbitrary texts to any language that is |
| 868 | supported by Django (as long as appropriate translation catalog exists, of |
| 869 | course). You can load translation catalog, activate it and translate text to |
| 870 | language of your choice, but remember to switch back to original language, as |
| 871 | activating translation catalog is done in per-thread basis and such change |
| 872 | will affect code running in the same thread. |
| 873 | |
| 874 | For example:: |
| 875 | |
| 876 | from django.utils import translation |
| 877 | def welcome_translated(language): |
| 878 | cur_language = translation.get_language() |
| 879 | try: |
| 880 | translation.activate(language) |
| 881 | text = translation.ugettext('welcome') |
| 882 | finally: |
| 883 | translation.activate(cur_language) |
| 884 | return text |
| 885 | |
| 886 | Calling this function with argument 'de' will give you ``"wilkommen"``, |
| 887 | regardless of :setting:`LANGUAGE_CODE` and language set by middleware. |
| 888 | |
| 889 | Function of particular interest are ``django.utils.translation.get_language()`` |
| 890 | which returns language used in current thread, and |
| 891 | ``django.utils.translation.activate()`` which activates translation catalog for |
| 892 | current thread. Other useful function is |
| 893 | ``django.utils.translation.check_for_language()`` checks if language is |
| 894 | supported by Django. |
| 895 | |