Skip to content

Instantly share code, notes, and snippets.

@araujo88
Created February 28, 2024 03:51
Show Gist options
  • Save araujo88/eb0e84d60443da2dd90eb9cbc6b47f29 to your computer and use it in GitHub Desktop.
Save araujo88/eb0e84d60443da2dd90eb9cbc6b47f29 to your computer and use it in GitHub Desktop.
Highlight go syntax in html

To create a div template in HTML that outputs formatted Go (Golang) code with syntax highlighting, you can use the popular JavaScript library called Prism. Prism is a lightweight, extensible syntax highlighter, built with modern web standards in mind. It's used to make code in HTML look pretty.

Here's how you can do it:

Step 1: Include Prism CSS and JavaScript

First, you need to include Prism's CSS and JavaScript files in your HTML document to apply the syntax highlighting. You can either download these files from the Prism website and host them yourself or use a CDN (Content Delivery Network) to include them directly.

<!DOCTYPE html>
<html>
<head>
    <!-- Include Prism CSS -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.26.0/themes/prism.min.css" rel="stylesheet" />
</head>
<body>

Step 2: Add Your Golang Code

You need to wrap your Golang code inside a pre tag followed by a code tag. To specify that the code is Golang, set the class attribute of the code tag to language-go. Make sure to encode any HTML characters within your code to their corresponding HTML entities, such as converting < to &lt; and > to &gt;.

    <!-- Golang Code with Syntax Highlighting -->
    <pre><code class="language-go">
package main

import "fmt"

func main() {
    fmt.Println("Hello, World!")
}
    </code></pre>

Step 3: Include Prism JavaScript

At the bottom of your HTML document, before the closing </body> tag, include Prism's JavaScript file. This script will automatically apply syntax highlighting to the code within the pre and code tags that have the appropriate classes.

    <!-- Include Prism JS -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.26.0/prism.min.js"></script>
</body>
</html>

Complete Example

Here's the complete HTML template that includes formatted Go code with syntax highlighting using Prism:

<!DOCTYPE html>
<html>
<head>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.26.0/themes/prism.min.css" rel="stylesheet" />
</head>
<body>

    <pre><code class="language-go">
package main

import "fmt"

func main() {
    fmt.Println("Hello, World!")
}
    </code></pre>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.26.0/prism.min.js"></script>

</body>
</html>

This will display the Go code with syntax highlighting on a webpage. You can explore more themes and plugins on the Prism website to further customize the appearance of the code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment