import re

def tex_escape(text):
    """
        :param text: a plain text message
        :return: the message escaped to appear correctly in LaTeX
    """
conv = {'&': '\\&', '%': '\\%', '$': '\\$', '#': '\\#', '_': '\\_', '{':
    '\\{', '}': '\\}', '~': '\\textasciitilde{}', '^': '\\^{}', '\\':
    '\\textbackslash{}', '<': '\\textless', '>': '\\textgreater'}
regex = re.compile('|'.join(re.escape(str(key)) for key in sorted(list(conv.
    keys()), key=lambda item: -len(item))))
return regex.sub(lambda match: conv[match.group()], text)
How can i escape latex special characters inside django templates