Drupal 8 override views field template in twig

Mon, 11/23/2015 - 22:39 -- meladawy

Its not well documented in drupal community so i had to mention this here. If you want to create twig template for one of your views field then the naming will be like this

views-view-field--{views machine name}--{page or block machine name}--{field name}.html.twig

Example

views-view-field--frontpage--page-1--nothing.html.twig

Here is the default template that you should override

{#
/**
 * @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 -}}

to access another field in views you should do something like this
{{ view.field.{field name}.original_value }}

{#
/**
 * @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
 */
#}
// in this case i access path field that i added in the same views
{{ view.field.path.original_value}}
 
{{ output -}}

Comments

I have copied views-view-field.html.twig file from core\templates\stable and put inside my theme's template folder.
Then I modified the file to just read {{ view.field.title.original_value}}, meaning I just want the title of each event to be displayed.

But titles for each event are coming up 4 times. How could I fix this?

Regards,
Subrata Sarkar

i also face same issue. But after exclude title i have figured out this issue.

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.