Adding google code prettify to blog

Note: I'm using yeoman, but you can manually download script extract parts and do all other boring stuff...

What is Google Code prettify?

Like its said on their page, it is a Javascript module and CSS file that allows syntax highlighting of source code snippets in an html code.

Simple way

I want to use it on my blog. It sounds easy, just include script from cdn in html, add class="prettyprint" to every <pre> tag and thats it.

<script src="https://google-code-prettify.googlecode.com/svn/loader/run_prettify.js"></script>

butt...

The problems

With this approach I had some issues:

  • this script is injecting css file that changes style of a <pre> tags, that transition was looking very ugly
  • the script includes additional scripts for handling a languages that i will never use. Although it is not a big problem, it can be easy solved together with the first one
  • i don't have an easy way of adding prettyprint class to a tags since I'm using md processor

Using with bower

This post is extension to my previous post (responsive blog layout with bootstrap)[responsive-blog-layout-with-bootstrap.html]. I've started using yeoman there, and bower is part of yeoman. You can find here google code prettify library as a bower component.

bower install --save google-code-prettify

I will include only main file, and lang-* files for language I think i will need.

They are calling lang-*.js files language handlers. There is a repo with additional handlers here

<script src="bower_components/google-code-prettify/src/prettify.js"></script>
<script src="bower_components/google-code-prettify/src/lang-css.js"></script>
<!-- Additional handlers here -->

Now I want to add classes to all <pre> tags. I was looking for more elegant solution than this, but I guess it has to be like this:

$('pre').addClass('prettyprint');
prettyPrint();

You will not see any changes because we haven't included any styles for code. I will use prettify.css, which is in src folder, copy it to my css file (in my case I'll make a copy and include it in less) and change it there. And that is it.

Author

I plan to write more articles about common laravel components. If you are interested let’s stay in touch.
comments powered by Disqus