Is there a way to showcase a block of Python code using a combination of HTML, CSS, and Javascript to enhance its

On my website, I want to display code blocks similar to how StackOverflow does it. The code block should be properly colored, formatted, and spaced out for better readability. All the code blocks on my site will be in python.

def func(A):
    result = 0
    n = len(A)
    while n > 1:
        n = n/2
        result = result + min(A[1,...,n])
    return result

The font style, background color, and spacing can be easily customized by defining a specific CSS class where the background is grey, the font is set to monospace, and appropriate spacing is applied.

My main concern is how to apply colors to different parts of the code. I assume that JavaScript can be used to loop through each word in the code block and map them to specific colors based on a predefined list of keywords or patterns.

If there are any incorrect assumptions or potential challenges in my approach, please let me know.

Answer №1

Latest Update as of May 14, 2021:

  • Enhanced code snippets to run smoothly even with the file:// protocol
  • Redirected CodeMirror's links to a reliable CDN source

Please note that these snippets still rely on an internet connection to download CodeMirror

Previous Update on November 9, 2020:

If you simply need code highlighting without a full-fledged editor, there is a lighter alternative available:

CodeMirror offers an addon specifically for code highlighting, omitting some advanced editing features like line numbers display. Nonetheless, it serves the purpose efficiently.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>CodeMirror RunMode Highlighting Example</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dcbfb3b8b9b1b5aeaeb3ae9ce9f2eaedf2ec">[email protected]</a>/lib/codemirror.min.css">
    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ef8c808b8a82869d9d809dafdac1d9dec1df">[email protected]</a>/addon/runmode/runmode-standalone.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="95f6faf1f0f8fce7e7fae7d5a0bba3a4bba5">[email protected]</a>/mode/python/python.min.js"></script>
  </head>
  <body>
    <pre><code id="python_code">def func(A):
    result = 0
    n = len(A)
    while n > 1:
        n = n/2
        result = result + min(A[1,...,n])
    return result</code></pre>
    <script type="text/javascript">
        window.onload = function(){
            var codeElement = document.getElementById('python_code');
            // Add code mirror class for coloring (default is the theme)
            codeElement.classList.add( 'cm-s-default' );
            var code = codeElement.innerText;

            codeElement.innerHTML = "";

            CodeMirror.runMode(
              code,
              'python',
              codeElement
            );
        };
    </script>
  </body>
</html>

Source:

Additionally, there is a "colorizer" addon for automatic colorization of pre elements. Refer to the CodeMirror manual for implementation details.

Original Answer

To incorporate CodeMirror's read-only mode within a code element, consider integrating one of the available language modes such as Python for syntax highlighting. The example demonstrates loading the library, setting up the appropriate language mode, and executing colorization upon page load by targeting the designated element ID. You can further customize the behavior by adjusting options like lineNumbers. Hope this solution meets your requirements :)

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>CodeMirror Read-only Highlighting Example</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6f0c000b0a02061d1d001d2f5a41595e415f">[email protected]</a>/lib/codemirror.min.css">
    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f4979b9091999d86869b86b4c1dac2c5dac4">[email protected]</a>/lib/codemirror.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="70131f14151d1902021f0230455e46415e40">[email protected]</a>/mode/python/python.min.js"></script>
  </head>
  <body>
    <pre><code id="python_code">def func(A):
    result = 0
    n = len(A)
    while n > 1:
        n = n/2
        result = result + min(A[1,...,n])
    return result</code></pre>
    <script type="text/javascript">
        window.onload = function(){
            var codeElement = document.getElementById('python_code');
            var code = codeElement.innerText;
          
            codeElement.innerHTML = "";
          
            var codeMirror = CodeMirror(
              codeElement,
              {
                value: code,
                mode: "python",
                theme: "default",
                lineNumbers: false,
                readOnly: true
              }
            );
        };
    </script>
  </body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to maintain the previous input value on page refresh in Vuejs?

In my development project, I am utilizing the Laravel and Vue.js technologies. I am facing an issue where I need to set the input value to its previous old value when either refreshing the page or navigating back to it in a Vue dynamic component. Here is ...

Extract the image URL from a JSON API

I'm struggling to retrieve an image URL from a Wordpress JSON API and populate an image tag with it. Below is the code that isn't working for me: $(document).ready(function() { $.getJSON('http://interelgroup.com/api/get_post/?post_id=46 ...

Creating a client-server application in JavaScript with the npm-net module

In my possession is a straightforward piece of code titled echo_server.js. It serves as a server that simply echoes back any text received from the connected client. var net=require('net'); var server=net.createServer(function (socket) { socke ...

Tips for integrating an infinite scroll feature using HTTP requests?

My current project involves developing a webapp using AngularJS to interact with a long array of objects. To display these objects on my index, I am utilizing nested ng-repeat functions. Additionally, I have implemented infinite scroll functionality simila ...

Tips for creating Selenium code to verify the asterisk symbol

Looking to create Selenium code for validating the presence of asterisks with mandatory fields such as First Name*, Last Name*, Enter Address*, and Enter Phone Number*. The validation needs to confirm the asterisk appears after each field name. Currently ...

issue with integrating promise in angular 4

I'm currently learning about promises and how to implement them in Angular. I have written the following code in StackBlitz. My goal is to display the array whenever it contains a value by using promises in Angular. This is my HTML code: <h2>A ...

What are effective ways to eliminate script tags from a webpage?

I have implemented tags on my website that users can use to interact with the site. My goal is to figure out how to make the browser only read text from a specific file I write, without any HTML. This should be restricted to certain sections of my websit ...

Transforming intricate JSON data into a structured table format

I'm struggling to transform the nested JSON data into an HTML table, but I keep encountering an error. I'm uncertain about where I may have made a mistake. Could it be related to how I am trying to access the array within the object? Here' ...

Having trouble with my Angular application, seems to be stuck at the loading screen. Not sure what's causing it, possibly

Hey there, I'm hoping to create a straightforward app that showcases posts. However, I've encountered an issue when deploying the initial page which is stuck on "Loading...". I believe it's a minor problem and would appreciate your assistan ...

Trigger Vue to scroll an element into view once it becomes visible

I created a dynamic form that calculates 2 values and displays the result card only after all values are filled and submitted, utilizing the v-if directive. Vuetify is my chosen UI framework for this project. This is the approach I took: <template> ...

Determining when all promises have either been rejected or resolved using vanilla JavaScript promises

In an effort to transition to loading all resources in my web application asynchronously using basic JS promises, I have implemented a ScriptLoader function. Below is the code snippet for the ScriptLoader used to load .js files: function ScriptLoader() { ...

Guide on sending a JavaScript variable as a URL parameter in Django

I need to pass a radio ID to my view, but I'm struggling with how to do it using the GET method in the URL: html: <a href="{% url 'maintenance_issue_fix' %}?radio_id=checked"> <img src="{% static 'images/ma ...

What is the appropriate overload to be selected when utilizing a ref in the method call?

Encountering an unfamiliar TS error while working with the code snippet below: <script lang="ts"> import {defineComponent, computed, toRef} from 'vue' import _ from 'lodash' import {DateTime} from 'luxon' int ...

Issue: The element '[object Object]' is of type 'object', which is not supported by NgFor. NgFor only works with Iterables like Arrays. - Problem encountered in an Ionic Project

I'm currently working on retrieving my user's username from Firebase Firestore Database using Ionic and AngularFire. I have implemented the valueChanges() method to obtain the observable and am trying to process it using an async pipe. However, u ...

Incorporating an element into a nested array

I have an array stored in a variable called 'items' with various products and their attributes. I am looking to randomly generate a popularity score between 1 and 100 for the items that currently do not have one. This is my current array: const ...

Upon transitioning from typescript to javascript

I attempted to clarify my confusion about TypeScript, but I'm still struggling to explain it well. From my understanding, TypeScript is a strict syntactical superset of JavaScript that enhances our code by allowing us to use different types to define ...

Retrieve the user's information using their email address

I am attempting to retrieve "Registered user information" on my email address using the "mail()" function. The mail() function is functioning correctly and successfully sending the email to the specified email address, however, it is unable to retrieve the ...

The navigation bar at the top of the page is causing content to be blocked on mobile screens, but not on desktop screens

My Fixed-Top navbar is causing an issue on mobile screens, as it is covering the top content of the page. This problem doesn't occur on PC screens. When I resize the browser width to fit a mobile screen, the navbar overlaps with the body content... &l ...

Conceal the countdown clock and reveal the message box

I am attempting to create a functionality where the text box will replace the timer when it reaches 0, and then the timer will be hidden. I am seeking a straightforward solution using either the 'v-show' or 'destroy' property in vue.js ...

What is the best way to transfer the API Response Time from one Fetch function to a separate asynchronous function?

After successfully obtaining the API Response Time (duration) using the 'makeAPICall' function, I am now faced with the task of passing this duration variable value to another asynchronous function. Can anyone assist me in finding a solution to a ...