@Jasper_Holton's 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.

View the photo from a post by @Jasper_Holton

@Jasper_Holton's profile photo

I added code embeds so now I can show off code directly on the site. I'm not supporting every language to start with, but a lot of languages are already supported. To add code, use *(language)* before the code you want to embed, and *** after the code. For example, here is some code below.

// Reload the suggested posts div with more posts
function reloadSuggested(){
    $.ajax({
    url : "/suggested/",
    success : function(result){ 
    document.getElementById("suggested").innerHTML = result;
        $('#reloadsuggested').on('click', reloadSuggested);
      }
    });
}
$('#reloadsuggested').on('click', reloadSuggested);


© Uglek, 2022

Terms of Use and Privacy Policy