0

I need to theme my view inside views template. Inside custom views-view.tpl.php template I can add individual fields inside loop:

<?php foreach ($view->style_plugin->rendered_fields as $delta => $item): ?>
<?php print $item['myfield1']; ?>
<?php endforeach; ?>
//after a loop I can add any other field for custom theming like so:
<?php print $item['myfield2']; ?>

Question: How can I add another field before the loop is executed? I tried this:

<?php print $item['myfield3']; ?>
<?php foreach ($view->style_plugin->rendered_fields as $delta => $item): ?>
<?php print $item['myfield1']; ?>
<?php endforeach; ?>
<?php print $item['myfield2']; ?>

But the field3 is not rendered because the $item is not defined, I think.

I am not php programmer so I came up with a dumb workaround

<?php foreach ($view->style_plugin->rendered_fields as $delta => $item): ?>
<?php endforeach; ?>
<?php print $item['myfield3']; ?>
//field is rendered
<?php foreach ($view->style_plugin->rendered_fields as $delta => $item): ?>
<?php print $item['myfield1']; ?>
<?php endforeach; ?>
<?php print $item['myfield2']; ?>

What is the correct way of displaying an individual field without putting it inside foreach loop?

Thank you

2

You are wise to admit it before someone else points it out: "I am not php programmer." ;) This is a pure PHP problem, having very little to do with Drupal.

Your foreach() loop defines the variables $delta and $item. Unlike some other languages, they are still in scope when the loop finishes, keeping the values they had at the end of the loop.

You could do something like this (untested):

<?php
  $first_item = reset($view->style_plugin->rendered_fields);
  $last_item = end($view->style_plugin->rendered_fields);
  print $first_item['myfield1'];
  pring $last_item['myfield2'];
?>

After the foreach() loop, $item would be the same as $last_item.

The PHP docs are pretty good: arrays and array functions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.