Theme coding conventions

Last modified: June 2, 2009 - 21:07

Theme authors should take care to write clean, well structured code just like a coder for any other project. Doing so makes the code easier to read, understand and maintain. While different organizations have different conventions, it's usually best to follow the Drupal standards as this helps when collaborating or asking for help.

  • Add 2 spaces for indents; rather than a tabbed indent (This maintains consistency and is consistent with Drupal's coding standards)
  • Match the indentation of long opening and closing block HTML tags
  • Distinguish between PHP and HTML indentation.

    Not this:

      ...
      <?php if ($header): ?>
      <div id="header">
        <?php print $header; ?>
      </div>
      <?php endif; ?>
      ...
       

    but this:

      ...
    <?php if ($header): ?>
      <div id="header">
        <?php print $header; ?>
      </div>
    <?php endif; ?>
      ...
       

    This makes it much easier to find matching opening and closing tags defined with different indentation.

  • Prefer PHP in HTML to HTML in PHP in templates. For example,

    not this:

    <?php
    if (!$page) {
      print
    "<h2><a href=\"$node_url\">$title</a></h2>";
    }

    if (
    $submitted) {
      print
    "<span class=\"submitted\">$submitted</span>";
    }
    ?>

    but this:

    <?php if (!$page): ?>
      <h2><a href="<?php print $node_url; ?>"><?php print $title; ?></a></h2>
    <?php endif; ?>

    <?php if ($submitted): ?>
      <span class="submitted"><?php print $submitted; ?></span>
    <?php endif; ?>
       

    After all, PHP is a HTML-embedded scripting language, and not the other way around.

  • Separate logic from presentation.
    You sometimes see:
    Price: <?php print $price; ?>
    Tax: <?php print $price * 0.075; ?>
  • Move the calculation up the code before you start the presentation of the data. The business logic part of the script would contain:
    <?php $tax = $price * 0.075; ?>
    and the presentation part:

    Price: <?php print $price; ?>
    Tax: <?php print $tax; ?>
  • Always put a semicolon at the end of your small PHP printing statements:
    <?php print $tax; ?> -- YES
    <?php print $tax ?> -- NO
  • In more extended sections of PHP code, follow the Drupal coding standards.
 
 

Drupal is a registered trademark of Dries Buytaert.