Highlight Your Code With a Django Regex Template Filter

intersexs profile photo

Highlight Your Code With a Django Regex Template Filter This is a Django template filter that uses python regex to highlight code. It works by using regular expressions to get all occurrences of code beginning with *(language)* followed by ***, in this example, (python) for the language. It then takes the code from these and including the language and formats it for an embed using PrismJS.com. The comments explain what each line of code does. In the below example, the *\** is escaped with concatenation (same with the HTML) to prevent it from messing up the template filter. One drawback of this is it does mean you can't use three stars (*) anywhere on a post with embedding (that's why I have it escaped).

@register.filter(name='embedcode') # Register the filter
def embedcode(value):
    sections = value.split("**" + "*") # Split by sections of code followed by delimiter
    rvalue = "" # Init return value
    for index, section in enumerate(sections): # Enumerate over the code blocks
        if index < len(sections)-1: # Add delimiter except for last block
            section = section + "**" + "*"
        scripts = re.findall(r"(\*\((\w+)\)\*([\d\D]+)\*\*\*)", section) # Three groups, a main group for the entire text, sub groups for language and code.
        dic = {} # Empty dictionary for find and replace
        for script in scripts: # Iterate through the scripts, get the language and code
            language = script[1]
            code = script[2]
            if language != 'language':
                dic[script[0]] = '<' + 'pre>' + '<' + 'code class=\"language-' + language + '\">' + code + '<' + '/code><' + '/pre>' # Add the embed code to the dictionary with the main group, language and code
        for i, j in dic.items(): # Find and replace
            section = section.replace(i, j)
        rvalue = rvalue + section
    return rvalue
Below is a photo of the regex in action.

Pinterest logo
Tumblr logo VK logo

https://uglek.com/post/283/? -

© Uglek, 2021

Terms of Use and Privacy Policy