I am looking for a solution to insert "something" every nth row in a view. Technically, that "something" will be an Ad, but in Drupal terms it could be a block, a node, an entity, custom html row...really anything that can point me in the right direction.
4 Answers
In under Theme: Information
you'll find Style output: views-view-table.tpl.php ...
. Override that. I selected the Theming info as opposed to other template overrides available because that is the one that has a foreach
for rows. In your override you can add a counter to the foreach()
along with an if($counter%10 == 0) { ... }
with some markup or call to a block or something like that.
-
It's best to add the extra stuff with a variable via a preprocessing, but I've found this more flexible than messing with the $view directly.– mpdonadio ♦Commented Dec 12, 2012 at 2:08
-
Agreed. If the user can get away with hook_views_pre_render() for hir use case, that's preferable.– bethCommented Dec 12, 2012 at 15:48
I would implement hook_views_pre_render. Loop through and append, edit, or create new entries into $view->result
as needed.
Using this approach you'd be injecting hand-picked stuff into your Views raw resultset and might be limited in your row style output unless you digged into Views quite a bit to override the row display handler (which I think is doable).
I think doing it in hook_views_post_execute works best.
<?php
/**
* Implements hook_views_post_execute().
*/
function my_module_views_post_execute(&$view) {
$entity_id = my_module_fetch_entity_id(); //Random function
$view->result[] = (object) [
'entity' => $entity_id,
];
}
Source: https://bitbucket.org/snippets/intracto/eax4/drupal-insert-an-entity-in-a-views-result
-
That is restricted to an entity though. What if it was arbitrary code or a snippet? Commented Jun 24, 2016 at 5:31
If you want to print custom code after every nth (for example 4th) row and keep the odd/even sequence you can simply edit default views template.
Place right into your theme's folder this file views-view-unformatted--taxonomy-term--page.tpl.php
with this code and you will see "Your custom code goes here" text after 4th row in default Taxonomy term views:
<?php foreach ($rows as $id => $row): ?>
<div class="<?php
switch ($id) {
case 1:
case 3:
case 4:
case 6:
case 8:
//add more IDs if you have more rows than 10 in your views
$myclasses = 'views-row-even row';
break;
default:
$myclasses = 'views-row-odd row';
}
print $myclasses; ?>"><?php print $row; ?></div>
<?php if ($id == 3): ?>
<div class="views-row-odd row">Your custom code goes here</div>
<?php endif; ?>
<?php endforeach; ?>
Based on this solution: http://www.jasom.net/how-to-add-custom-code-adsense-after-first-row-in-drupal-7-and-drupal-8-views-one-line-solution
tpl
for the view and do whatever..