Auto-escaping code blocks in Reveal.js
Join the DZone community and get the full member experience.
Join For FreeWarning - this falls into the "Cool, but may not be a good idea category." I'm a huge fan of the Reveal.js framework for HTML-based presentations and I've already posted a few of my utilities/tips/etc for making it work better (or at least better for me). One issue I've run into a few times lately is escaping HTML for code slides.
Reveal.js has great support for code coloring (color coding?). Here's a quick screen shot of an example:
In general this works simple enough. Here is how a typical code slide would look.
<section> <h1>Testing Code</h1> <pre> var x = 1; var y = 2; var z = "Do people even read my code samples?"; var zz = "I mean really, are *you* reading this?"; </pre> </section>
But if you want to include HTML in your slide then you run into a problem. As you might expect, your HTML will be rendered as, well, HTML, not source code. Typically this isn't a huge deal. Code samples are short and if you type fast, you can replace < and > in a few minutes, but after doing this a few times, and preparing to do some slides focused on HTML5 development, I thought there might be a cooler way.
By default, Reveal.js initializes itself immediately. I modified the code to do this after the DOMContentLoaded event and did some hacking:
document.addEventListener("DOMContentLoaded", init, false); function init() { console.log("Run my init, yo!"); var cblocks = document.querySelectorAll("pre code"); if(cblocks.length) { for(var i=0, len=cblocks.length; i<len; i++) { var dom = cblocks[i]; var html = dom.innerHTML; html = html.replace(/</g,"<").replace(/>/g,">"); dom.innerHTML = html; } } // Full list of configuration options available here: // https://github.com/hakimel/reveal.js#configuration Reveal.initialize({ controls: true, progress: true, history: true, center: true, //i cut some stuff out here to save space in the code block }); }
As you can see, I simply make use of querySelectorAll to find all of my code blocks. (I could make that selector a bit more precise.) I then simply grab the HTML, escape the < and > characters, and then update the innerHTML property.
Voila!
Published at DZone with permission of Raymond Camden, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Trending
-
Competing Consumers With Spring Boot and Hazelcast
-
From On-Prem to SaaS
-
Extending Java APIs: Add Missing Features Without the Hassle
-
Transactional Outbox Patterns Step by Step With Spring and Kotlin
Comments