This blog uses PrismJS for syntax coding but everytime I switch themes, it can be difficult to modify. For example, I use Ghost for my CMS and if I use any of the built-in themes, it's not very easy to modify them. Therefore, here is my approach to adding syntax coding without having to modify the theme at all. I simply paste this code within the Site Header or Site Footer.
Step 1 - Use cdnjs
to get the latest version of PrismJS
<!-- PRISM JS for Syntax Coding -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism-twilight.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/prism.min.js"></script>
Step 2 - Add any PrismJS plugins
<!-- PRISM JS Line Numbers Plugin -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/plugins/line-numbers/prism-line-numbers.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/plugins/line-numbers/prism-line-numbers.min.js"></script>
Step 3 - Customize
A lot of my code blocks have use back ticks but do not include the prefix language-
. Therefore, upon each page load, I need to dynamically check to see if there are any classes within the <code>
block and if not then append a language prefix.
<script>
// Use the JSON Coloring to later add it to language-bash
Prism.languages.json = {
'property': {
pattern: /(^|[^\\])"(?:\\.|[^\\"\r\n])*"(?=\s*:)/,
lookbehind: true,
greedy: true
},
'string': {
pattern: /(^|[^\\])"(?:\\.|[^\\"\r\n])*"(?!\s*:)/,
lookbehind: true,
greedy: true
},
'comment': {
pattern: /\/\/.*|\/\*[\s\S]*?(?:\*\/|$)/,
greedy: true
},
'number': /-?\b\d+(?:\.\d+)?(?:e[+-]?\d+)?\b/i,
'punctuation': /[{}[\],]/,
'operator': /:/,
'boolean': /\b(?:false|true)\b/,
'null': {
pattern: /\bnull\b/,
alias: 'keyword'
}
};
Prism.languages.bash = Prism.languages.json;
// Convert every <code> into <code class=language-powershell>
var codeArray = document.getElementsByTagName('code');
for(var i = 0; i < codeArray.length; i++){
// If missing language, add one
if(codeArray[i].classList == ''){
codeArray[i].classList.add("language-bash");
}
// Add Line Numbers to Code
codeArray[i].classList.add("line-numbers");
console.log(`${i} ${ codeArray[i].classList }`);
}
</script>
Subscribe to new posts
Processing your application
Please check your inbox and click the link to confirm your subscription
There was an error sending the email