@Jasper_Holton's profile photo

Universal Language Translation Django Template Tags This is a Django template tag for universal translation, that is, translation from any language to the clients' language. It uses locale middleware to work and otherwise consists of app filters that translate the text as needed. The code is commented in order to describe what each piece does. The first part is the settings, where we need to add locale middleware so we can get the request.LANGUAGE_CODE.

# settings.py
MIDDLEWARE = [
    '...',
    'django.middleware.locale.LocaleMiddleware' # Add this to the end
]
And the template tags, as well as a filter.
# templatetags/app_filters.py
from django import template # Imports
from googletrans import Translator
from langdetect import detect # Detect language
register = template.Library() # Initialize template library and translator
translator = Translator()

@register.simple_tag(takes_context=True) # Pass context so we can get the language code
def etranslate(context, value): # Translate from english
    request = context['request'] # Get request context
    lang = request.LANGUAGE_CODE # Get language code
    if(request.GET.get('lang', '') != ''): # Override with URL parameter if there is one
        lang = request.GET.get('lang', '')
    if lang == None: # Fallback for none
        lang = 'en'
    translation = None # Init translation
    if not lang == 'en': # Translate only if language isn't english
        try:
            translation = translator.translate(value, dest=lang, src='auto').text # Auto translate
        except:
            translation = None # No translation on error
    if translation != None:
        return translation # Return translation
    return value # Return untranslated text on error

@register.simple_tag(takes_context=True)
def translate(context, value): # Translate from any language
    request = context['request']
    lang = request.LANGUAGE_CODE
    if(request.GET.get('lang', '') != ''):
        lang = request.GET.get('lang', '')
    if lang == None:
        lang = 'en'
    translation = None
    if not value == '' and not detect(value) == lang: # If the text isn't already in the users language
        try:
            translation = translator.translate(value, dest=lang, src='auto').text
        except:
            translation = None
    if translation != None:
        return translation
    return value

@register.filter(name='detectlanguage') 
def detectlanguage(value): # Detect the language
    return detect(value) # Return value (en, es, de, etc)
In action, the tag looks like {% etranslate 'Text here' %}. For an English client, this isn't translated by the site and just shows in English. For anyone else, the text is translated to their language (or at least an attempt is made). For non-English translations, such as a post that could be in German or Dutch, use {% translate 'Text here' %} for universal translation from any language to the browser language or language passed by a URL parameter lang. Also, I use the template filter detectlanguage with text on the site, {{ post.content|detectlanguage }} to display the language of posts next to them.


Pinterest logo
Tumblr logo VK logo

https://uglek.com/post/300/ -

© Uglek, 2022

Terms of Use and Privacy Policy