Using Drupal 8 preprocess views view field was a bit tricky so I set up these snippets that should help
In your theme’ YOURTHEME.theme
/**
* Implements hook_preprocess_form_element().
*/
function YOURTHEME_preprocess_views_view_field(&$variables) {
// Print all the keys to see what you have available
print_r(array_keys($variables));
// Name of the field
echo $variables['field']->field;
$variables['new_variable'] = "";
// Do something based on the name of the field
if ($variables['field']->field == 'field_NAME_OF_YOUR_FIELD') {
// Modify the actual output
$variables['output'] = "add your custom" . $variables['output'];
// And OR add new variable that will be readable in your TWIG file
$variables['new_variable'] = "";
}
}
Be sure to replace YOURTHEME with the actual name of your theme and field_NAME_OF_YOUR_FIELD with the actual machine name of your field.
In your themes views-view-field.html.twig
{#
/**
* @file
* Default theme implementation for a single field in a view.
*
* Available variables:
* - view: The view that the field belongs to.
* - field: The field handler that can process the input.
* - row: The raw result of the database query that generated this field.
* - output: The processed output that will normally be used.
*
* When fetching output from the row this construct should be used:
* data = row[field.field_alias]
*
* The above will guarantee that you'll always get the correct data, regardless
* of any changes in the aliasing that might happen if the view is modified.
*
* @see template_preprocess_views_view_field()
*
* @ingroup themeable
*/
#}
{{ output -}}
{%- if new_variable is not empty -%}
<p>
Do something based on the new variable
</p>
<p>
{{ new_variable -}}
</p>
{% endif %}
Cheers!
Hi, it’s not working.
the new_variable is not working.
the output too.
Hi Mark,
Q0: Did you clear the cache?
Q1: is the template file loading at all? in your child theme’s views-view-field.html.twig add some test text: AAAA see if it prints.
Q2: Did you both of these?
Be sure to replace YOURTHEME with the actual name of your theme And field_NAME_OF_YOUR_FIELD with the actual machine name of your field.
Q3: Is your preprocess function working? in here
function YOURTHEME_preprocess_views_view_field(&$variables) {
..
print(“BBBBBBBB”); // se if this prints at all
..}
Start with these debugging questions, and go from there.
why it does not work for me please help me 🙁
the preprocess does not work it does not enter in the preprocess function..
I don t know if drupal 8 version or what?
so helpful ! I had no idea how to change the content in drupal 8 custom views field templates. Thank you
RossA
Thank you for you kind comment,
Cheers!
Lehel
Thanks, it works great. We can even retrieve the number of results in views-view-field.html.twig. I used it to manage the singular and plural of the category name.