You are here

Changing an argumentative view title

Submitted by cafuego on 8 December, 2010 - 15:54

Using the taxonomy view to change how taxonomy listings are displayed is rather nifty. However, I found myself being asked by a client to make sure the page title (ie: the taxonomy term as set by the argument) was properly title-cased. That issue comes up from time to time on the #drupal-support IRC channel, so I suspected it would be easy, as many people had done this.

I found hook_views_pre_render(), in which I assumed I could change a value in the $view object, which would then be rendered to the browser. Sadly changing the only title attribute I could find on the object had no effect on the final output. Then a bunch of googling found me increasingly arcane ways of trying to accomplish my task, culminating in a way to tweak the internals of the $view object via PHP code in the argument validator. However, I decided to file that under the just because you can doesn't mean you should code library.

A smart person on IRC then suggested I just call drupal_set_title() in whatever views hook I deemed appropriate. Huzzah! Based on the documentation, I chose hook_views_post_render(). This is triggered after all processing of content has been done, so you're working with the completed view output.

So what I can do now is test which view is being displayed to the user, extract what it thinks its title should be, and then override that. Of course, it should not title-case the title if it already contains a capital letter. This allows for the user to know better and specify preferred capitalisation for a taxonomy term.

And here is the final result, a hook that changes the taxonomy page view title to title-case, but only if it was all lower case to start with:

<?php
/**
* Implementation of hook_views_post_render().
*/
function mymodule_views_post_render(&$view, &$output, &$cache) {
if ($view->name == 'taxonomy_term' && $view->current_display == 'page') {
$title = $view->build_info['title'];
if (strtolower($title) == $title) {
drupal_set_title(ucwords($title));
}
}
}
?>