How to theme views fields in Drupal 7 correctly

mechmsk picture mechmsk · Mar 28, 2012 · Viewed 17k times · Source

I need to theme views in Drupal 7. There is a content type 'Book' and I need to list 5 books and theme them in special manner(preview image, title and author).

When I override views-view-field.tpl.php and print raw SQL result, I see that all fields are displayed. This code

echo "<pre>";
print_r($row);
echo "</pre>";

gives

[entity] => stdClass Object
 (
  [title] => ...
  ....
  [nid] => 34
  ...
  [body] => Array
  ...

But I don't want pass [body] from database to php side, because it can be huge and cause a performance issue. I haven't selected [body] in view settings.

Is there a way to pass only certain fields to views-view-field.tpl.php?

Thanks in advance.

Answer

Joe Hyde picture Joe Hyde · Oct 22, 2012

The variables available are written in the documentation inside the sites/all/modules/views/theme folder's files.

Usually, the variable you need to look at and modify on a views-view-fields.tpl.php template is $fields

I use the devel module (http://drupal.org/project/devel) to view the variables available:

<?php
//after enabling the devel module...
dpm($fields);

// This will print a Kuomo display on the page with the array's vars

?>

Generally, on a view of nodes,

<?php print $fields['title']->content; ?> 

will print the node title. For fields, try

<?php print $fields['field_FIELDNAME']->content; ?>

If you have the memory, you can capture ALL vars available on the template in the Kuomo with

<?php dpm(get_defined_vars()); ?>

Make sure you clear your cache before you try to view the vars.