The prism.js documentation states
Prism forces you to use the correct element for marking up code:
<code>. On its own for inline code, or inside a<pre>for blocks of code - https://prismjs.com/#features-full
We're using a document management system, that does not allow any HTML code inside a <pre> tag
<pre>some code</pre> - formatting is correct, but no syntax highlighing<code>some code</code> - syntax highlighing works, but all line breaks/indentations are removed by the CMS<pre><code>some code</code></pre> - transformed to <pre><code>some code</pre> by the CMSIs there a way to have prism.js add syntax highlighting to a <pre> tag, like this:
<pre class="language-javascript">
if (test) {
someCode();
}
</pre>
Maybe there's a plugin or a JS configuration to tell prism.js to highlight those <pre> tags.
I was able to do it. Here is the code, I don't think you need the language-js how I do it later...
<pre class="language-js">
var cheese = sandwich;
function(){
return "hello!";
}
</pre>
First I init prism and follow the Manual Highlighting from the docs:
<script>
window.Prism = window.Prism || {};
window.Prism.manual = true;
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.23.0/prism.min.js"></script>
Now nothing happens by default. Further down the docs, they show an example under Usage with Node
// The code snippet you want to highlight, as a string
const code = `var data = 1;`;
// Returns a highlighted HTML string
const html = Prism.highlight(code, Prism.languages.javascript, 'javascript');
So in my example I do the following:
<script>
// Get the pre element
let pre = document.querySelector("pre");
// Grab the text out of it
let code = pre.innerText;
// Highlight it
let highlighted = Prism.highlight(code, Prism.languages.javascript, 'javascript');
// Now put that back in, but as HTML
pre.innerHTML = highlighted
</script>
Example here:
https://codepen.io/EightArmsHQ/pen/f9023daaa6499786e25899cb62f4d6c2?editors=1010
I'm sure you can figure out how to querySelectorAll the pre tags and loop through each formatting them : )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With