Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding Syntax highlighting to webpages (HTML/php)

I'm using http://softwaremaniacs.org/soft/highlight/en/ to Syntax highlight HTML. I've got a php loop pulling code from a wordpress. I'm using the pre / code tags in my code and the following loop to pull the code from wordpress.

<?php while (have_posts()) : the_post(); ?>
<p><i><?php the_date(); echo "<br />"; ?> </p></i>
<h2><?php the_title(); ?></h2>    
<p><?php the_content(); ?></p>
<?php endwhile;?>

At the top of my php page I've got the import...

<script type="text/javascript" src="highlight.pack.js"></script>
<script type="text/javascript">
hljs.initHighlightingOnLoad();
</script>

The test.html on the page works fine but my page doesnt seem to on my web server. Is it something to do with the way I'm dynamically pulling content? How would I make this work?

like image 878
Skizit Avatar asked Sep 08 '26 09:09

Skizit


2 Answers

From the source code

function initHighlightingOnLoad() {
    var original_arguments = arguments;
    var handler = function(){initHighlighting.apply(null, original_arguments)};
    if (window.addEventListener) {
      window.addEventListener('DOMContentLoaded', handler, false);
      window.addEventListener('load', handler, false);
    } else if (window.attachEvent)
        window.attachEvent('onload', handler);
    else
        window.onload = handler;
}

So this will work only once, BUT

You can call the method again by tricking the plugin

hljs.initHighlighting.called = false;
hljs.initHighlighting();

I've tested it on the demo page and seems to work pretty well.

So you might need to call this two lines after you insert new elements on the page.

like image 184
BrunoLM Avatar answered Sep 09 '26 22:09

BrunoLM


A possible alternate approach: use GeSHi to do the syntax highlighting in PHP.

An example from their documentation:

//
// Include the GeSHi library//
include_once 'geshi.php'; 
//// Define some source to highlight, a language to use
// and the path to the language files//
$source = '$foo = 45;
for ( $i = 1; $i < $foo; $i++ ){
  echo "$foo\n";  --$foo;
}';$language = 'php';
 //
// Create a GeSHi object//
 $geshi = new GeSHi($source, $language);
 //
// And echo the result!//
echo $geshi->parse_code();
like image 32
Nathan Long Avatar answered Sep 09 '26 22:09

Nathan Long