In AnQi CMS, managing content, especially documents containing code, you may wish that code blocks can be presented in a beautiful and easy-to-read manner, which usually requires 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 to 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 with a few simple steps.
The autoCMS provides 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 conversion process is only structural, and it will not add color, font styles, and other highlighting effects to the code.To achieve this, we need to use a JavaScript library on the front end.
Enable Markdown content rendering
Firstly, make sure that your security CMS system is correctly configured to render Markdown content.In the AnQi CMS backend, you can usually find the option to enable Markdown editor under 'Global Settings' -> 'Content Settings'.archiveDetailinContentMarkdown written in the field) will be automatically converted to HTML. For example, in the template using{% archiveDetail archiveContent with name="Content" render=true %}{{archiveContent|safe}}whenrender=trueParameters are the keys that ensure 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 need to be HTML-escaped so that JavaScript libraries can recognize and process the generated<pre><code>Label.
Introduce front-end syntax highlighting library
The key to implementing syntax highlighting is on 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 code language type (such as JavaScript, Python, HTML, etc.) to achieve syntax highlighting.
Here we take a popularhighlight.jsas an example to demonstrate how to integrate it into your security CMS template.
Step 1: Select and import the highlight style sheet
highlight.jsProvided a variety of theme styles for you to choose from.You need to select a CSS file that matches the design style of your website.These files are usually obtained through CDN (Content Delivery Network) services to improve loading speed.
In your CMS template file, find the public header file of your website, which is usually located/templatethe directory.base.htmlor a similar global template file. In this file,<head>add your selectedhighlight.jsTopic 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 choosemonokaiordraculaetc:
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.8.0/styles/monokai.min.css">
第二步:Introduce the highlight JavaScript library
Similarly inbase.htmlthe file<head>within the tag (or placed for optimization loading,)</body>before the end of the tag), introducehighlight.jsthe core JavaScript file:
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.8.0/highlight.min.js"></script>
Third step: Initialize syntax highlighting
Inhighlight.jsThe script has been loaded. You need to call its initialization function to scan the page and apply highlighting.This is typically executed after the page content is fully loaded.highlight.min.jsAfter that, or place in your custom JavaScript file, make sure to execute after the DOM is loaded.
An common practice is, inbase.htmlof</body>Just before the tag ends, follow byhighlight.min.jsAfter the introduction of, add the following code:
<script>
document.addEventListener('DOMContentLoaded', (event) => {
document.querySelectorAll('pre code').forEach((block) => {
hljs.highlightElement(block);
});
});
</script>
This code listensDOMContentLoadedEvent, make sure that the HTML document is fully loaded and parsed before execution. It selects all the<pre><code>elements, and applieshighlight.jssyntax highlighting.
In Markdown specify the code language
In order tohighlight.jsThe ability to accurately identify and highlight code in different programming languages requires you to explicitly specify the code language in Markdown code blocks. 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))
When you publish content containing these Markdown code blocks, Anqi CMS will convert it to one withclass="language-javascript"orclass="language-python"such attributes.<pre><code class="language-xyz">tags,highlight.jsCan automatically identify and apply the correct syntax highlighting according to these class names.
Summary
By enabling Markdown rendering in the AnQi CMS and in the website's frontend template (such asbase.html) to introducehighlight.jsThis syntax highlighting library's CSS and JavaScript files, combined with a simple initialization script, allow you to make code blocks in Markdown content shine.This not only improves the readability of the code, but also greatly enhances the user reading experience, making the technical content more attractive.
Common Questions (FAQ)
1. Why does the code block not highlight after I follow the steps?Please check several key points:
- Is Markdown rendered correctly to HTML?Confirm that your content editor's Markdown rendering function is enabled, and that it is used to call content in the template
render=trueParameters (e.g.,){% archiveDetail ... render=true %}) and|safeFilter. - Is the CDN link valid?Check the imported
highlight.jsThe CSS and JS file CDN links can be accessed normally, without 404 errors. - Did JavaScript initialization succeed?Ensure
highlight.jsThe initialization code (for example)hljs.highlightAll();) inhighlight.jsThe library is loaded correctly and there are no JavaScript errors preventing its execution.You can open the browser developer tools (F12) to check if there are any errors in the console. - Has the code language been specified?Ensure that the language type is specified at the beginning of the Markdown code block (e.g., `)
javascript),this helps highlight the library to identify the code type.
2. Can you change the highlight theme?Of course you can.highlight.jsMultiple built-in themes are provided. You just need to change thebase.htmlpath of the CSS file introduced in.default.min.csswithmonokai.min.css, or visithighlight.jsVisit the official website to see more themes and their corresponding CDN links. Clear the browser cache and refresh the page to see the new theme effects.
3. If my website has already included jQuery, do I need to modify the initialization code?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>
Please ensure that this jQuery code is included after the jQuery library file andhighlight.jsthe library file is imported.