6

I have a view with a bunch of fields and I'm styling those fields in:

views-view-fields.html.twig

In my .theme file I'm also using a preprocess function to pass additional variables to the above template.

function theme_preprocess_views_view_fields(&$vars) {
  $vars['my_var'] = 'hello';
}

So in the twig template, I'm able to do something like:

{% for field in fields -%}
  {{my_var}}
{%- endfor %}

This is working like a charm for the first loaded fields, but when I hit "Load More" or I use exposed filters to filter down the view, the other loaded elements will not have my_var.

Now, "kinting" my_var directly in the template file. I saw that my_var is NULL for all other elements loaded after with Ajax and this made me think that the problem is with theme_preprocess_views_view_fields being called once, the first time the page is loaded and completely being ignored from the Ajax call.

Shouldn't this preprocess be called and handled by the Ajax call Drupal is doing on the view itself?

If not, is there a way to query Drupal to re-run this hook when other elements are loaded?

Thanks!

  • 1
    "kinting" haha that made my day. – No Sssweat Aug 23 '16 at 14:20
  • :) glad it did! Do you have any suggestions as well ? – Drupalotto Aug 23 '16 at 14:31
  • @Drupalotto did you try turn off cache of your views? Just check the reason. – Jonh Jul 25 '18 at 7:21
  • @neetu morwani .. – Jonh Jul 25 '18 at 7:44
  • Caching in the views is off. Does not seem like caching issue. Hook_preprocess_views_view is not called when next set of rows are being called via Ajax pager? Is there any way to preprocess variable array rows coming from AJAX? – neetu morwani Jul 26 '18 at 4:06
2
+25

In template "views-view-fields.html.twig" there is a three variables returned : "view", "fields", "row" you can see this here .

So to add your custom variables you need to put it into these three variables like below

 function dt8_preprocess_views_view_field(&$vars)
  {
    $vars['row']->my_var = 'Hey';
  }

and in our template "views-view-fields.html.twig" we print int like this

{{ row.my_var }}
| improve this answer | |

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.