Drupal - How do I create a custom template for view?

To create custom template for that view, create file and give name to that template as views-view-fields--viewname--page/block.html.twig and then create the HTML structure and then simply print the field accordingly and then save the file and don't forget to flush the cache.

To print the field...suppose you want to print the title and image field then do as below {{ fields.title.content}} {{fields.machine_name_of_image_field.content}} thats it.

Note: To get the machine name of the field, goto the content type and then manage fields, there you will find machine name of those fields. And remember if you have not add field in view in admin panel and adding it in your template file then it will not reflect.


Below give are the views template suggestion allowed in Drupal 8.

  • views-view--foobar--page.html.twig
  • views-view--page.html.twig
  • views-view--foobar.html.twig
  • views-view.html.twig
  • views-view-unformatted--foobar--page.html.twig
  • views-view-unformatted--page.html.twig
  • views-view-unformatted--foobar.html.twig
  • views-view-unformatted.html.twig
  • views-view-fields--foobar--page.html.twig
  • views-view-fields--page.html.twig
  • views-view-fields--foobar.html.twig
  • views-view-fields.html.twig

Refer Views template files for more information.


Create a services.yml file (an example file is under sites/default)

In that file, set debug: true (set to false in example file)

Save the file and clear you cache.

If you go to your view and inspect the code it will show you all of the theme suggestions you can use (similar to what theme info did in Views 3)

Tags:

Views

Theming

8