@Jasper_Holton's profile photo

Tag-Preserving Translation Template Block Filter This is a block translation template filter, for translating a block of text into any language from English on a Django website. You can use this filter to translate an entire page of text using Python.

 # templatetags/app_filters.py
from django.template.base import Node # Imports
from googletrans import Translator
from langdetect import detect
from django.contrib import messages

translator = Translator() # Initialize translator and template library
register = template.Library()

def translatevalue(lang, input): # A method to translate HTML while preserving styles
    values = input.splitlines() # Split the html
    output = '' # Init outputs
    translations = list()
    strippedvalues = list()
    for value in values: # For each value
        stripped = ''
        try: # Try to strip the tags
            tagsplit = value.split('>', 1);
            otag = tagsplit[0] + '>'
            ctag = '<' + tagsplit[1].split('<', 1)[1]
            stripped = tagsplit[1].split('<', 1)[0]
            if(len(stripped) > 0): # If they contain something
                translations.append(translator.translate(stripped, dest=lang, src='en').text) # Translate that
                translations.append("") # Or store no translation
            strippedvalues.append(stripped) # Saved the stripped value
            translations.append("") # Fallback
    for x in range(len(values)): # Build the translated text
        output = output + values[x].replace(strippedvalues[x], translations[x]) + '\n'
    return output # Return it

# The tag
def blocktranslate(parser, token):
    nodelist = parser.parse(('endblocktranslate',))
    return TranslateNode(nodelist)

# The node
class TranslateNode(template.Node):
    def __init__(self, nodelist):
        self.nodelist = nodelist
    def render(self, context): 
        input = self.nodelist.render(context) # Get the HTML
        lang = context['request'].LANGUAGE_CODE # Get the language code and querystring
        if(context['request'].GET.get('lang', '') != ''):
            lang = context['request'].GET.get('lang', '')
        if lang == None:
            lang = 'en'
        translation = ''
        if not lang == 'en':
            translation = translatevalue(lang, input) # Translate if the user language isn't english
        if translation != '': 
            return translation # Return the translation
        return input
This template tag looks like {% blocktranslate %}Some text here{% endblocktranslate %}. I use it to translate whole pages, like the TOS and Privacy. It's much quicker to implement than using the single-line template filter.

@Jasper_Holton, likes this,

Pinterest logo
Tumblr logo VK logo

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

© Uglek, 2022

Terms of Use and Privacy Policy