
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
else:
translations.append("") # Or store no translation
strippedvalues.append(stripped) # Saved the stripped value
except:
translations.append("") # Fallback
strippedvalues.append(stripped)
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
@register.tag
def blocktranslate(parser, token):
nodelist = parser.parse(('endblocktranslate',))
parser.delete_first_token()
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
@Jasper_Holton, likes this,
Comments (0) Comment
© Uglek, 2022