I wanted a simple way to show java code samples in HTML pages. My workflow involves writing all my content using Google Docs and copying and pasting into an LMS (D2L). However, copy & paste rarely works as intended. Code, in particular, lost a lot of formatting – or at least, it was inconsistent.
My colleague suggested using js-beautify, but found that the original intent was slightly different (or at least that’s what I think?), so I kept running into issues. All I really wanted to do was simplify the publishing process for easily embedded code samples.
My new workflow?
The magic happens with the following
<script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.10.0/beautify.min.js"></script> <script src="https://cdn.jsdelivr.net/gh/google/code-prettify@master/loader/run_prettify.js?autorun=false"></script
<script type="text/javascript"> $(document).ready( function() { $(".code").each(function(index) { var codeDiv = $(this); var indentFixed= js_beautify(codeDiv.html()); codeDiv.html(indentFixed); codeDiv.addClass("prettyprint"); }); PR.prettyPrint(); }); </script>
The js files in the first few lines are for jQuery, beautify, and prettify from various CDN’s.
The actual code just runs through the DOM finding any pre tags with class “code” then beautifies first (which fixes indentation). When it’s done beautifying, it will prettyfy, which is the “PR.prettyPrint()” line which works in tandem with the option “&autorun=false”
Prettyfy will usually just find the “prettyprint” class objects and insert <span> tags according to its algorithm, so I wanted it to hold off until I automatically indented things, because the two libraries were fighting with each other.
In the end, all I have to do now is include the code above in every page and have my code in <pre class=”code”> tags.
<pre class="code"> public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World"); } } </pre>
The above code was intentionally badly formatted, but, through beautifying and prettyfying, it ends up looking like (note that the following is an image):
Want to add line numbers?
https://stackoverflow.com/questions/8399547/how-to-add-line-numbers-to-all-lines-in-google-prettify
<script type="text/javascript"> $(document).ready( function() { $(".code").each(function(index) { var codeDiv = $(this); var indentFixed= js_beautify(codeDiv.html()); codeDiv.html(indentFixed); codeDiv.addClass("prettyprint linenums"); }); PR.prettyPrint(); }); </script> <style> .linenums li { list-style-type: decimal; } </style>
Then, you get (again, it’s an image):
Resources: