Beginners Tutorial for Views 2 Theming: Creating an alternative block for recent comments

After I got my first actual comment last night (yeah!), I wanted to add the “most recent comments” as a block in the sidebar. Drupal comes with a block for that purpose, but I wasn’t happy with the way the block displayed the comments. I remembered that I very much liked the way Typepad displays comments (e.g. like this on a friends blog).

I wanted to display the name (linking to the person’s homepage), the word “comment” (linking to the actual comment), the title of the story (linking to the story itself), and the date. So in toto, something like this: “Daniel Hanold added a comment to Story Name X (5 days ago)”.

Obviosuly, I created a view that displays comments that were recently created. I attached that view to this story for reference. However, I couldn’t get the ouput of that view to display what I wanted. First of all, all the labels were added before the data and were followed by a colon. Views theming, here I come. Usually, there’s tons of great documentation and examples for pretty much any module. For views theming however, I didn’t find anything that explained the concept well and gave some easy to understand examples, so here’s a tutorial to the easiest possible theming of a view output.

Like I said, the output I wanted was “Daniel Hanold added a comment to Story Name X (5 days ago)”. The output views gave me by default was “added a: Daniel Hanold to comment Story X 5 days ago”. Using views theming, I wanted to do a couple of things:

  • Remove the colon
  • Have the label show up behind the data
  • Add parenthesis around the date

To do that, go to your view and click on “Theme: Information”. This gives you a lot of theming information about all the things you can theme. Since this is going to be a basic tutorial, I’ll only talk about the row style output of the data fields.

On this page, you can find one link that’s called “Row style output”. With a file such as views-view-fields–stories-recent-comments.tpl.php (this goes into your theme directory), you can style the general output of all fields of this view. Using that template, I was able to remove the colon and have the labels show up behind the data fields. I attached this file for reference as well. The one remaining thing was adding parenthesis around the data. With a file called views-view-field–stories-recent-comments–block–timestamp.tpl.php, you can style the output of just that one data field, in this case the date (see attached file).

Upload those two files to your server, go back to your view, click on “Theme: Information” and then click on “Rescan template files” for the new templates to be activated. After you’ve added all those steps, you have a nice “recent comments” block that looks like this:

File Downloads