24 June 2017

[Data Science] Embedding Python Codes in Blogger Using SyntaxHighlighter

You know, I have been rendering my R codes to a html files in R Markdown (RMD), then copied the whole HTML codes to paste into blogger.

What I needed was to embed code snippets.

I came across this awesome post to do just that, using SyntaxHighlighter, credit goes to the blogger and the creator of SyntaxHighlighter. And not forgetting StackOverflow.

Here's an example:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import h5py

Now it's a success! Now I can share my data science stuffs here with proper code snippets!

Yay~

Here are the details of setting it up, as some of the steps in the links mentioned are outdated:

In Blogger:

1. Go to Template > Edit HTML (it is a small icon below the blog preview).

2. Copy and paste these codes immediately after the <head> tag:
<script src='http://alexgorbatchev.com/pub/sh/2.1.364/scripts/shCore.js' type='text/javascript'></script>
<script src='http://alexgorbatchev.com/pub/sh/2.1.364/scripts/shBrushPython.js' type='text/javascript'></script>
<link href='http://alexgorbatchev.com/pub/sh/2.1.364/styles/styles/shCore.css' rel='stylesheet' type='text/css' />
<link href='http://alexgorbatchev.com/pub/sh/2.1.364/styles/shThemeDefault.css' rel='stylesheet' type='text/css' />
(In the link provided, the quotation marks in the links are presented as '&#x27;' - Blogger does not accept it)

3. Save the template.

4. Go to Layout.

5. Add a HTML/Javascript Gadget - Any location will do. I chose one at the side bar.

6. Add a title for the gadget. Remember this title because you have to locate it later in the HTML code in order to hide the gadget. Use SyntaxHighlighter if you can't think of one.

7. In the content box, include this code:
<script class='javascript'>//<![CDATA[
SyntaxHighlighter.config.clipboardSwf = 'http://alexgorbatchev.com/pub/sh/2.1.364/scripts/clipboard.swf';
SyntaxHighlighter.all();
//]]></script>
8. Save the gadget.

9. Now, head back to Template > Edit HTML. Locate the widget id of the gadget you just added in. It can be found within the b:widget tag. (It is HTML1 for me.)

10. Locate the <b:skin> ... </b:skin>. Expand it and before the ]]></b:skin>, include this code to hide the gadget:
#HTML1 {display:none;}
11. Save the template and all is good to go!

Note: Somehow it does not work in Preview.


~Huat

No comments:

Post a Comment