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.