How to implement syntax highlighting for code blocks in Markdown content rendered to HTML?

Calendar 👁️ 103

In AnQi CMS, managing content, especially documents containing code, you may want the code blocks to be presented in a beautiful and easy-to-read manner, which usually requires implementing syntax highlighting.Markdown as a lightweight markup language makes content creation simple and efficient, and the built-in Markdown editor of Anqi CMS is even more powerful.How can you achieve syntax highlighting for code blocks when Markdown content is rendered into HTML?This is not the default system function, but it can be easily realized through simple configuration steps.

AnQi CMS offers great flexibility in content processing. When you use the Markdown editor to write articles in the background and insert code blocks, the system is responsible for converting the Markdown syntax (such as code enclosed by three backticks `) into the corresponding HTML structure (usually<pre><code>...</code></pre>However, this transformation process is only structural, and it will not add color, font styles, or highlighting effects to the code.To achieve this, we need to use a JavaScript library on the front-end.

Enable Markdown content rendering

First, make sure that your CMS system is properly configured to render Markdown content.In the AnQi CMS backend, you can usually find the option to enable Markdown editor under the "Global Settings" and "Content Settings".Once enabled, you will be able to enter content in the article field (such as document details tagarchiveDetailinContentMarkdown written in the field) including code blocks will be automatically converted to HTML. For example, when using templates,{% archiveDetail archiveContent with name="Content" render=true %}{{archiveContent|safe}}then,render=trueThe parameter is the key to ensure that Markdown content is correctly converted to HTML.|safeThe filter is used to indicate to the template engine that this content is safe and does not require HTML entity encoding so that the JavaScript library can recognize and process it generated<pre><code>.

Introduce the front-end syntax highlighting library

The key to implementing syntax highlighting is in the front-end. There are many excellent JavaScript libraries on the market that can complete this task, such ashighlight.jsorPrism.js. They work by scanning predefined code tags on the page (such as<pre><code>),then apply the preset styles and structure based on the language type (such as JavaScript, Python, HTML, etc.) to highlight the code.

Here we take a popular onehighlight.jsas an example to demonstrate how to integrate it into your Anqi CMS template.

Step 1: Select and introduce the highlight style sheet

highlight.jsA variety of theme styles are provided for you to choose from. You need to pick a CSS file that matches your website design style.These files are usually accessible through CDN (Content Delivery Network) services to improve loading speed.

In your AnQi CMS template file, find the public header file of your website, which is usually located/templateUnder the directorybase.htmlor a similar global template file. Add your chosen<head>tag within the file.highlight.jsTheme CSS link. For example, if you like the “default” theme:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.8.0/styles/default.min.css">

If you want a dark theme, you can choose:monokaiordraculaand so on:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.8.0/styles/monokai.min.css">

Second step: Introduce the Highlight JavaScript library

Similarly, inbase.htmlthe file<head>Inside the tag (or to optimize loading, place)</body>Before the tag ends), introducehighlight.jsThe core JavaScript file:

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

Step 3: Initialize syntax highlighting

Inhighlight.jsAfter the script is loaded, you need to call its initialization function to scan the page and apply highlighting.This is usually executed after the page content is fully loaded. You can add this JavaScript code to the includehighlight.min.jsAfter that, or place in your custom JavaScript file, make sure to execute after the DOM is loaded.

It is a common practice to add,base.htmlof</body>immediately before the end tag,highlight.min.jsafter the introduction of,

<script>
    document.addEventListener('DOMContentLoaded', (event) => {
        document.querySelectorAll('pre code').forEach((block) => {
            hljs.highlightElement(block);
        });
    });
</script>

This code listensDOMContentLoadedAn event to ensure that the HTML document is fully loaded and parsed before executing. It will select all elements in the page.<pre><code>and applyhighlight.jssyntax highlighting.

Specify code language in Markdown

In order tohighlight.jsAccurately identify and highlight code of different programming languages, you need to specify the language in the Markdown code block explicitly. This is done by adding the language name after three backticks:

```javascript
// 这是一个JavaScript代码块
function greet(name) {
  console.log(`Hello, ${name}!`);
}
greet("World");
# 这是一个Python代码块
def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)

print(factorial(5))

After you publish the content containing these Markdown code blocks, AnQi CMS will convert it to haveclass="language-javascript"orclass="language-python"etc. properties<pre><code class="language-xyz">tag, highlight.jsIt can automatically identify and apply the correct syntax highlighting based on these class names.

Summary

By enabling Markdown rendering in Anqi CMS and in the website's front-end template (such asbase.html) to introducehighlight.jsThis CSS and JavaScript file of this syntax highlighting library, combined with a simple initialization script, allows you to make code blocks in Markdown content shine.This has enhanced the readability of the code and greatly improved the user reading experience, making the technical content more attractive.


Frequently Asked Questions (FAQ)

1. Why did I follow the steps, but the code block didn't get highlighted?Please check several key points:

  • Is Markdown rendered correctly to HTML?Confirm that the Markdown rendering function of your content editor is enabled and that it is used when calling content in the templaterender=trueParameters (for example{% archiveDetail ... render=true %}), and|safefilter.
  • Is the CDN link valid?Check the importedhighlight.jsThe CDN link of the CSS and JS files can be accessed normally, no 404 errors.
  • Did the JavaScript initialization succeed?Ensurehighlight.jsThe initialization code (for examplehljs.highlightAll();athighlight.jsThe library loaded correctly and there were no JavaScript errors preventing its execution.You can open the browser developer tools (F12) to check if there are any errors in the console.
  • Does the programming language specify?Ensure that the language type is specified at the beginning of the Markdown code block (for example, `javascript), which helps the highlighter library identify the type of code.

2. Can you change the highlight theme?Of course you can.highlight.jsMultiple built-in themes are provided. You just need to change the path of the CSS file included inbase.html. For example, changedefault.min.cssReplacemonokai.min.cssor visithighlight.jsVisit the official website to see more themes and their corresponding CDN links. After changing, clear the browser cache and refresh the page to see the new theme effect.

3. Do I need to modify the initialization code if my website has already included jQuery?If your website has included the jQuery library, you can simplify the initialization code. For example, use jQuery's$(document).ready()method to ensure that the DOM is loaded before execution:

<script>
    $(document).ready(function() {
        $('pre code').each(function(i, block) {
            hljs.highlightElement(block);
        });
    });
</script>

Make sure this jQuery code is after the jQuery library file andhighlight.jsthe library file is included.

Related articles

Does AnQiCMS support the configuration of a custom Markdown renderer?

In the daily operation of AnQiCMS, we often encounter refined needs for content presentation, especially for those who are accustomed to writing content in Markdown, it is natural to be concerned about whether the system supports the configuration of custom Markdown renderers.In fact, Markdown, with its concise and efficient features, has become the preferred choice for many content creators.From the design philosophy of AnQi CMS, it is committed to providing an efficient, customizable, and easy-to-expand content management solution.

2025-11-08

How to troubleshoot exceptions when displaying mathematical formulas or flowcharts in a Markdown editor on the front end?

In Anqi CMS, the Markdown editor brings us great convenience, especially when we need to insert mathematical formulas or draw flowcharts.By concise syntax, we can easily express complex concepts.However, sometimes after using these advanced features, they may not display as expected, but instead display exceptions, such as only displaying the original Markdown text, or some content cannot be parsed.Don't worry when encountering such problems. This is usually not a problem with the safety CMS itself, but rather a problem with some link in the configuration, content writing, or frontend loading process.

2025-11-08

How to introduce the necessary JavaScript library for Markdown rendering in the `base.html` file?

AnQiCMS provides a convenient and efficient Markdown editor for content creators, allowing us to easily organize article structure, insert code blocks, and images.However, when our content needs to display complex mathematical formulas or clear flowcharts, relying solely on the Markdown syntax itself is not enough to present them beautifully on the web.These advanced features require the introduction of specific JavaScript libraries on the browser side to be correctly parsed and rendered.

2025-11-08

After Markdown editing, do you need additional CDN resources to support MathJax or Mermaid?

In AnQi CMS, the addition of the Markdown editor undoubtedly brings great convenience to content creation, especially for users who need to write technical documents, academic papers, or complex explanations, the ability to directly insert mathematical formulas (MathJax) and flowcharts (Mermaid) is an even more delightful feature.However, whether additional CDN resources are needed to support the display of these advanced Markdown elements is a consideration many users will have before using them.From the actual operational experience

2025-11-08

How to automatically generate an article table of contents (TOC) based on Markdown content?

How to effectively organize the structure of long articles while managing website content with Anqi CMS, which is a worthy issue to pay attention to.Automatically generate an article table of contents (Table of Contents, abbreviated as TOC) is a very practical solution.It not only allows readers to quickly understand the outline of the article, but also makes it convenient for them to jump to the parts of interest, while also helping search engines better understand the structure of the article.

2025-11-08

How to extract the HTML content rendered from Markdown without destroying the tag structure?

In content operation, we often encounter such needs: on a list page of articles or a special topic page, it is necessary to display the summary content of the articles.These articles are usually written using a Markdown editor, which may contain images, links, bold text, and other rich HTML structures.If simply truncating the HTML string rendered by Markdown, it often breaks the original tag structure, causing the page layout to become chaotic, even resulting in unclosed tags, which seriously affects the user experience.AnQi CMS as an efficient

2025-11-08

How does the `truncatechars_html` filter precisely control the character truncation length of HTML content?

In website operation, how to effectively display content is an eternal topic.We hope users can quickly browse information and also be attracted by the精彩的 abstract, and then click to view the full text.However, when the original content is long and contains complex HTML structures, how to elegantly reduce it has become a challenge that template designers and content operators often encounter.Bluntly cutting a segment of text with HTML tags by character count may destroy the original HTML structure.

2025-11-08

How to safely truncate a Markdown-rendered HTML content by words?

In content operation, we often need to display a brief version of the content on list pages, aggregation pages, or article summary areas.This not only optimizes the page layout and improves user experience, but also helps search engines better understand the content theme to some extent.However, when content is written in Markdown format and finally rendered as HTML, if you need to truncate it, you may encounter some challenges.It is easy to truncate HTML content by characters or bytes, which can easily lead to incomplete tags, disordered page structure, and even display errors.

2025-11-08