2

After having solved How to calculate the average Fivestar rating correctly?, I have a computed field Average score that displays the average score of a node. I sometimes want to display this field in a View as a rating (e.g. 4.2/5) and add some more markup to it. For the moment, I have different templates of the form views-view-field--MY-VIEW--field-average-score.tpl.php with the same code:

<?php $rating = round(($output/100) * 5, 1); ?>
<span>
  <span class="star"></span><span><?php print $rating . '/5'; ?></span>
</span>

Having all these duplicate templates seems silly to me. Is there a way to only have one and somehow point out which Average score fields should be styled accordingly? Simply using views-view-field--field-average-score.tpl.php is not what I want, since I don't always want to style Average score like this.

2

Then you can do it like this:

Use view-field--field-average-score.tpl.php which will affect all views that have this field, but we can add an if statement to target the views you only want the special markup.

Ex: In here we check if it has view_name with block_1 OR view_name_2 with block_1

<?php if (($view->name == 'view_name' && $view->current_display == 'block_1') || ($view->name == 'view_name_2' && $view->current_display == 'block_1'): ?>
<?php $rating = round(($output/100) * 5, 1); ?>
<span>
  <span class="star"></span><span><?php print $rating . '/5'; ?></span>
</span>
<?php else: ?>
<?php print $output; ?>
<?php endif; ?>

In case you are wondering, current_display is the machine name

The $view->current_display check is optional. This is so it only affects a certain Display of block/page that is inside your view.

So for line 1, you could use this instead:

<?php if ($view->name == 'view_name' || $view->name == 'view_name_2'): ?>

If you want to affect all blocks/pages that are inside these 2 views.

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.