2012/08/08

Setup blogger with syntax highlighting

Before I will post the first source code I was looking how to setup syntax highlighting with blogger.com. For anyone who would like to know:

http://mlawire.blogspot.de/2009/07/blogger-syntax-highlighting.html

Very simple :)

EDIT 2012/08/14:
It wasn't as simple as I thought. After digging arount a little i found how to do it properly.
This links helped me out:

http://derkan.blogspot.de/2011/11/adding-syntaxhighlighter-to-blogger.html

Basically you have to copy the content of the css files you will use under Templates->Customize->Advanced->Add Css

I used the files

https://github.com/alexgorbatchev/SyntaxHighlighter/blob/master/styles/shCore.css
https://github.com/alexgorbatchev/SyntaxHighlighter/blob/master/styles/shCoreDefault.css

After clicking Apply to Blog you can add the code from the derkan blog to your post. I modified the code for my needs like this:

<div style="display:none">
<pre class="brush:js"></pre>
<pre class="brush:csharp"></pre>
</div>

<script type="text/javascript">
 function loadScript(url, callback){
  var script = document.createElement("script")
  script.type = "text/javascript";
  if (script.readyState){  //IE
   script.onreadystatechange = function(){
    if (script.readyState == "loaded" ||
      script.readyState == "complete"){
     script.onreadystatechange = null;
     callback();
    }
   };
  } else {  //Others
   script.onload = function(){
    callback();
   };
  }
  script.src = url;
  document.getElementsByTagName("head")[0].appendChild(script);
 }
 loadScript("http://alexgorbatchev.com/pub/sh/current/scripts/shCore.js", 
  function(){
   loadScript("http://alexgorbatchev.com/pub/sh/current/scripts/shAutoloader.js", 
    function(){
     SyntaxHighlighter.config.bloggerMode = true;
     SyntaxHighlighter.autoloader(
             'c# c-sharp csharp http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCSharp.js',
'js jscript javascript http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJScript.js'
     );     
     SyntaxHighlighter.all();
    }  
   );
  }
 );
</script>

The invisible div forces the load of all scripts, you wan't to use. Without this div it could happen, that you would get an error saying: brush XYZ not found.

Infos about the autoloader script you can find here.



No comments:

Post a Comment