Search code examples
drupaldrupal-7drupal-theming

Formatting HTML output of theme function


I've implemented my own theme function (theme_my_theme_function) and have implemented hook_theme to tell Drupal about my function. Everything works correctly and I get the output I want on the page, except...

When I look at the HTML source code, all the HTML code outputted by my function is all in one long line! How do I get my theme function to output formatted HTML that is neat and easy to read?


Solution

  • If you want the HTML to be formatted, you're going to have to do it yourself when you build the HTML strings. The easier way to do that is to use a template file as opposed to building strings of HTML manually (remember that PHP is essentially a HTML template language). There is a pretty good write up of how to do that here: http://drupal.org/node/165706

    The core node module has a pretty good example:

    node.module:

    <?php
    
    /**
     * Implementation of hook_theme()
     */
    function node_theme() {
      return array(
        'node' => array(
          'arguments' => array('node' => NULL, 'teaser' => FALSE, 'page' => FALSE),
          'template' => 'node',
        )
      );
    }
    

    node.tpl.php:

    <div id="node-<?php print $node->nid; ?>" class="node<?php if ($sticky) { print ' sticky'; } ?><?php if (!$status) { print ' node-unpublished'; } ?> clear-block">
    
    <?php print $picture ?>
    
    <?php if (!$page): ?>
      <h2><a href="<?php print $node_url ?>" title="<?php print $title ?>"><?php print $title ?></a></h2>
    <?php endif; ?>
    
      <div class="meta">
      <?php if ($submitted): ?>
        <span class="submitted"><?php print $submitted ?></span>
      <?php endif; ?>
    
      <?php if ($terms): ?>
        <div class="terms terms-inline"><?php print $terms ?></div>
      <?php endif;?>
      </div>
    
      <div class="content">
        <?php print $content ?>
      </div>
    
      <?php print $links; ?>
    </div>
    

    There may also be a way to integrate HTMLTidy into Drupal so that it "beautifies" the markup before it's output, but I've never done that myself.

    Ultimately, I would highly recommended not worrying about the formatting of your HTML output. Instead, use Firebug for Firefox or Inspector for Chrome/Safari. These both have an "Inspect Element" tool that lets you view the markup of the page in a nice browsable, editable tree. It's invaluable for web development.

    *EDIT* theme_item_list does minimal formatting of HTML output. Here is an example of a list generated by theme_item_list:

    <div class="item-list"><ul><li class="first">1</li> 
    <li>2</li> 
    <li>3</li> 
    <li class="last">4</li> 
    </ul></div>
    

    In the code for theme_item_list you can see that it just adds a "\n" after the <li>:

    $output .= '<li' . drupal_attributes($attributes) . '>' . $data . "</li>\n";