Chapter Three LLC

HOWTO: Use Different Node Templates by Node Variables (nid, type, view)

Farsheed Hamidi-Toosi

With node template files you are often limited to something like node.tpl.php and node-blog.tpl.php. Often times it’d be nice to make a different template for just one specific node or a different template for teaser/list view and full node view.

Using the PHP code below, Drupal will look for these template files, split by page or no page view. This gives more fine grained control over your node tpl.php files.

Page view:

1) node-[nid]-page.tpl.php
   Node by itself on a page, specific NID
2) node-[type]-page.tpl.php
   Node by itself on a page, specific type
3) node-default-page.tpl.php
  Node by itself on a page, default

Listing/Teaser view:

4) node-[nid].tpl.php
   Node in list/teaser, specific NID
5) node-[type].tpl.php
   Node in list/teaser, specific type
6) node.tpl.php
   Node in list/teaser, default.

*UPDATE* Earl Miles has shown this can be done much simpler than what I had previously. Revised code below.

Place this code in your template.php file in your theme’s directory.

<?php
function _phptemplate_variables($hook, $vars = array()) {
  switch (
$hook) {
    case
'node':
     
// Here is the way to switch to a different node-<something> template based on node properties.
     
if ($vars['page']) {
       
// This is LIFO (Last In First Out) so put them in reverse order, i.e
        // most important last.
       
$vars['template_files'] = array('node-default-page', 'node-'. $vars['node']->type .'-page', 'node-'. $vars['node']->nid .'-page');
      }
      else {
       
$vars['template_files'] = array('node-'. $vars['node']->nid);
      }
      break;
  }

  return
$vars;
}
?>

HOWTO: Write Cleaner tpl.php Files

Farsheed Hamidi-Toosi

The PHPTemplate system in Drupal is a powerful theming system. However, because it is written in PHP it is easy to abuse since it is possible to directly inject PHP logic into the templates. This often creates the effect of HTML-IN-PHP which is not good.



HTML-IN-PHP:

<?php
print '<h2 class="title">'. $title .'</h2>';
?>

PHP-IN-HTML:

<h2 class="title">
<?php print $title ?>
</h2>

Which do you think a themer who understands HTML/CSS will understand better? Of course the second, because it is mostly HTML and the themer can modify the HTML tags quite easily.

Conditional Statements

Another example of this is with logic statements.

HTML-IN-PHP:

<?php
global $user;
if (
$user->uid) { ?>


<h2 class="title">You are now logged in!</h2>

<?php } ?>

PHP-IN-HTML

<?php global $user; ?>
<?php if ($user->uid): ?>

<h2 class="title">You are now logged in!</h2>

<?php endif; ?>

See how the second example is easier to read? It’s also broken up into small pieces that a themer can move around quite easily. Having open and closing braces for an if statement is really hard to follow. But if(conditional): and endif; statements are easy to read, and “chunkify” or “modularize” the text in a clear way.

<?php if ($test == TRUE): ?>

<!— Block of HTML to printout if TRUE —>

<?php endif; ?>

PHPTemplate variables

The last thing that can make your life and the themer’s life easier is to pass variables to the template files using phptemplate_variables. A tpl.php really should be mostly simple conditional statements and print statements. If you have PHP code spanning multiple lines or are working with arrays or something, you can probably pull that code out of the tpl.php and put it in template.php.

Example Node.tpl.php with too much PHP

<?php
if ($node->field_related[0]['nid']) {
 
$related_cck_node = node_load($node->field_related[0]['nid']);
  print
'<div class="related-cck-link">';
  print
l($related_cck_node->title, 'node/' . $related_cck_node->nid);
  print
'</div>';
}
?>

Why is all that logic in the tpl.php? You can move that out into template.php.

Using Template.php to add variables to your tpl.php files

<?php
function _phptemplate_variables($hook, $vars = array()) {
  switch(
$hook){
    case
'node':
      if (
$vars['node']->field_related[0]['nid']) {
       
$related_cck_node = node_load($vars['node']->field_related[0]['nid']);
       
$vars['related_cck_link'] = l($related_cck_node->title, 'node/' . $related_cck_node->nid);
      } 
      break;
  }
  return
$vars;
}
?>

Now the node.tpl.php file will get a new variable called $related_cck_link which you can easily print out.

Example Node.tpl.php file with logic removed

<?php if ($related_cck_link): ?>
  <div class="related-cck-link">
    <?php print $related_cck_link ?>
  </div>
<?php endif; ?>

HOWTO: Quickly Truncate a Block of Text

Farsheed Hamidi-Toosi

When theming things I run into situations where a block of text is too long and I need a really quick way to truncate text and append an ellipses or custom trailing text. The built in drupal teaser truncates text in a much more logical manner (watches out for html tags and the like) while this php snippet is simpler and meant to run on pure text. You can do strip_tags() if you want to remove all the html tags before running this code on your piece of text. I often just drop this into my template.php and use it in various spots in the theme.

<?php
/**
* Truncate the string if it is beyond a certain $length and append with an ellipses or custom text
* $length is the number of characters allowed before truncating
* $append is appended to the truncated string
*/
function your_theme_custom_truncate($string = '', $length = 30, $append = '&#8230;') {
  return
strlen($string) > $length ? trim(substr($string, 0, $length)) . $append : $string;
}
?>

Before:

Suspendisse potenti. Ut tempus auctor libero. Aliquam molestie dolor quis lectus. Curabitur et erat eget lorem nonummy ultrices. Mauris interdum. Etiam imperdiet viverra purus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris sem mauris, feugiat at, dictum vitae, placerat nec, odio. Nulla fringilla. Morbi justo nulla, commodo quis, ultricies a, eleifend eu, ante. Morbi eget erat eu ante tincidunt interdum. Nullam at est. Nulla ultrices pede vitae sapien bibendum bibendum. Quisque turpis enim, ullamcorper at, fermentum quis, vulputate quis, libero. In facilisis, dui eget accumsan molestie, justo metus tempor quam, eu tempor ipsum eros a urna. Donec aliquet. Curabitur condimentum volutpat augue. Praesent bibendum commodo enim.

After:

Suspendisse potenti. Ut tempus auctor libero. Aliquam molestie dolor quis lectus. Curabitur
et erat eget lorem nonummy ul…

Five Steps to Writing Better Documentation

Farsheed Hamidi-Toosi

Documentary films, when successful, offer the viewer an intimate glimpse into a situation as it unfolds. There is often a progression or growth that occurs through the film, as every mistake and every twist and turn is captured candidly. It’s captivating because it tells a story “as it happens” instead of recounting or remembering a story after it has happened.

So why should software documentation be any different?!

Imagine a film documentary where the director didn’t really think anybody was going to watch it, so they half-ass the editing process or just decide to skip filming some days. The end product would be a pretty incomplete documentary. Sound familiar?

The analogy may sound silly, and I doubt any software documentation will be as interesting as a well-made documentary film, but why is most software documentation so BAD? We’ve all encountered confusing, vague, incomplete documentation and the reason is most likely because people regard documentation as an afterthought. It is often minimalistic and leaves out many details that the general reader needs - more a footnote for the original author than for anybody else.

This makes for really boring or confusing documentation. Since the author is documenting something they have just finished, the information is not thorough or particularly valuable. They (developers and users) want to know what the author was thinking when they wrote it, why they wrote it, pitfalls, and would like to understand the author’s experience in a compact form. This means not glossing over details, and it also means not providing unrelated or distracting information.

It may seem like a daunting process to document software, and that is probably because:

a) Developers are allergic to writing.
b) Developers enjoy being as cryptic as possible (d0cum3nt4t!0n i5 14m3, d00d!!!)
c) People try to document things after they happen, which feels like a lot of work.

While I’m sure a) and b) have something to do with it, people more likely write bad documentation because they try and do it after they are finished. Nooo! It’s like taking a fascinating video documentary and summarizing the entire thing on a post-it-note. Somehow, not as thorough… ;)

It’s really easy to write good documentation, and the secret is to *document things as they happen* and not after they happen. If you notice something or realize something while you are working, just write it down somewhere, keep a running list, and most importantly: DON’T LEAVE ANYTHING OUT. Even if you think it’s obvious, it may not be obvious to the next person, and sometimes it’s not even obvious when you go back and read it yourself! Remember that you are documenting a process, so editing things out is NOT encouraged. Later on if you need to, you can go back and edit things that are extraneous or confusing.

The amazing thing about this process is that it FEELS like less work, because you aren’t forcing yourself to remember things. In some cases, it can help you plan out what you are working on, too.

Five Steps to Writing Better Documentation

1) Write things down as they happen.

If you are describing how to configure something, actually walk through it yourself, keeping clear notes as you go. Keep a running list somewhere, and don’t leave out details. The extra few seconds after each step to document will pay off later. Additional information like screenshots and simple examples help immensely.

2) Try not to make any assumptions about your audience.

Provide relevant details or links to background information where appropriate. If you do make assumptions, state them at the top, i.e. “This document assumes the reader has a working knowledge of PHP.”

3) Organize the results.

A simple outline (you know with roman numerals and stuff) works well. Try to envision a newbie reading your documentation, then a more experienced person. The idea is that good documentation works in levels - so that a reader can see the “big picture” immediately but also can examine the details if they need to.

4) Revise, revise, revise.

Documentation evolves over time. Your audience may be unclear about how something works or why you did something or may need more details. Keep revising until they stop bugging you! :) This is the stage where you trim the fat, so to speak.

5) Put on your scarlet smoking jacket.

Bask in the everlasting glow of your work with a glass of wine near a crackling fire.


You don’t have to be an expert on a subject to write good documentation. An expert tends to automatically make more assumptions, but newbies have a fresher perspective. Since most readers will be newbies themselves, they’ll be able to relate to the author’s tone and language as well. On the other hand, experts can explain things more thoroughly and concisely from a technical point of view. Both perspectives provide valuable insight on how something works.

Lastly, have fun with it! Throw in some jokes or drop a reference to P. Diddy once in a while. Reading this stuff can be agonizing so your readers will thank you for waking them up. ;)

Syndicate content