To set up Google Code Prettify on your Blogger blog for syntax highlighting, follow these steps:
Add the Prettify CSS and JavaScript
- Go to your Blogger Dashboard.
- Navigate to Theme > Edit HTML.
- Find the <head> section of your template.
Insert the following lines just before the closing </head> tag:
<link href='https://cdn.jsdelivr.net/gh/google/code-prettify@master/loader/prettify.css' rel='stylesheet'/>
<script src='https://cdn.jsdelivr.net/gh/google/code-prettify@master/loader/run_prettify.js'></script>
Use Code Blocks in Your Posts
- When writing a blog post, switch to the HTML view (click "HTML" in the post editor).
- Wrap your code using <pre> and <code> tags, and add the prettyprint class:
<pre class="prettyprint">
<code>
function helloWorld() {
console.log("Hello, world!");
}
</code>
</pre>
3. Optional: Specify Language for Better Parsing
You can help Prettify detect the language by adding a language class:
<pre class="prettyprint lang-js">
<code>
// JavaScript code
var x = 42;
</code>
</pre>
Common language classes:
- lang-js – JavaScript
- lang-html – HTML/XML
- lang-css – CSS
- lang-python – Python
- lang-java – Java
Handle Unescaped HTML in Code Blocks
If your code contains unescaped HTML characters (e.g., <, >, &), Prettify may not render them correctly. To fix this, add the following script just before the closing tag to automatically escape these characters within
tags, while avoiding double-escaping already escaped entities:
WOKING ON IT << the Challenge
This script runs after the page loads, finds all <code> elements within <pre class="prettyprint">, and converts unescaped HTML characters to their proper entities before Prettify processes them. .
Preview and Publish
- Preview your post to ensure code is highlighted correctly.
- Publish when satisfied.
✅ Tips:
- Prettify automatically highlights all elements with class="prettyprint" on page load—no extra JavaScript needed.
- Escape your code. <. > and & all cause challenges with blogger, so showing code is a challenge, creating a script to do that for us is even more of a challenge.
- For dark themes, you can replace the CSS link with a themed version (e.g., sons-of-obsidian.css):
<link href='https://cdn.jsdelivr.net/gh/google/code-prettify@master/loader/skins/sons-of-obsidian.css' rel='stylesheet'/>
Now your code snippets will be cleanly formatted and syntax-highlighted using Google Code Prettify.
No comments:
Post a Comment