Snippets of Code
Adding syntax highlighting into Tumblr

After much googling around, I found two popular ways to add syntax highlighting into Tumblr:

  1. Alex Gorbachev’s Syntax Highlighter
  2. Google’s Prettify

I tried the Syntax Highlighter at first and spent a really long time trying to get it to work. When it finally did, it slowed the loading time by a huge amount, so I switched to the Prettify.

Prettify was a lot simplier to install. The code below automatically adds the prettyprint class to any <code> tag. Alternatively, you can leave out the script and add the class manually.

<!-- For Syntax Highlighting -->
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.css"></link>  
<script src="http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.js"></script>  
<script>
    function styleCode() {
        if (typeof disableStyleCode != 'undefined') { return; }

        var a = false;
        
        $('code').each(function() {
            if (!$(this).hasClass('prettyprint')) {
                $(this).addClass('prettyprint');
                a = true;
            }
        });

        if (a) { prettyPrint(); } 
    }

    $(function() {styleCode();});
</script>

This assumes you don’t already have jQuery.

When posting code, use a text editor to change all the angle brackets to &lt; and &gt; and enclose it in <pre><code></code></pre> tags. The <pre></pre> is necessary to keep the formatting.

Note: The highlighting won’t show up in RSS feeds or the dashboard.

  1. ximili reblogged this from snippets-of-code
  2. csjoshi04 reblogged this from snippets-of-code
  3. wobblyrobotears reblogged this from snippets-of-code
  4. paulodiovani reblogged this from snippets-of-code and added:
    Uma das primeiras coisas que fui procurar quando comecei a postar no Tumblr foi um plugin ou script para adicionar...
  5. guinee-conakry-tourisme reblogged this from snippets-of-code
  6. aradianofftester reblogged this from snippets-of-code
  7. andreasleicher reblogged this from snippets-of-code and added:
    Nice way to add syntax highlighting to code in tumblr:
  8. jwilf reblogged this from snippets-of-code
  9. pezcuckow reblogged this from snippets-of-code and added:
    It’s surprisingly easy...your blog (or any website): Google has
  10. evolutiondesign reblogged this from snippets-of-code and added:
    Think I’ll need...this for some of my posts….