Display Formatted Code Within A Drupal Article

One of the features that really sets Drupal apart from other CMSs is its' filter system - the ability for Drupal to run standard text data through functions, called filters, that will alter the text in some useful way. Out of the box, Drupal 7 offers several filters by default. For example, the 'Filtered HTML' input format will run several filters, doing things like removing potentially harmful javascript, closing missing HTML tags, and adding paragraph tags where appropriate.

A commonly requested feature for tech and development related sites is the ability to post code (such as PHP or Javascript) within an article and display it in some meaningful way. HTML provides the <pre> tag, which displays fixed-width text while preserving line breaks and indenting - it's intended for posting computer code on a page - but in my experience, Drupal doesn't seem to play nice with <pre> tags. Also, we want PHP code to have syntax highlighting. For example:

= array('orange','apple','banana');
foreach (
$fruits as $fruit) {
"Yum, I sure would like a $fruit.\n";

The best way I've found to get this accomplished is with the codefilter module. This makes displaying nicely formated code stupid easy. First, just install and enable the module. Then you just need to enable the new filter for the input formats that you want to be able to display formatted code. To do that go to Admin > Configuration > Text Formats. Then click 'Configure' next to the input format you're editing and enable the 'Code Filter' checkbox.

Now whenever you want a block of code to have codefilter formatting, simply wrap it in <code> </code>. If you want to include php syntax highlighting, wrap the php code in <?php ?>. If the formatting doesn't appear right away, don't forget to clear your site cache. Enjoy!

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
Enter the characters shown in the image.
glqxz9283 sfy39587stf02 mnesdcuix8