http://redcrackle.com/blog/drupal-8/theme-views-templates
In this post, you will learn how to theme Drupal 8 views by overriding default views templates and use our own markup to build an accordion (based on bootstrap 3 accordion). We will begin by identifying a custom theme for our newly installed Drupal 8 site and add bootstrap 3 css and javascript files.
This is all we need to create a new theme.
1 2 3 4 5 6 7 | ©À©¤©¤ demotheme.info.yml ©À©¤©¤ demotheme.libraries.yml ©À©¤©¤ css ©¦ ©À©¤©¤ bootstrap-theme.min.css ©¦ ©¸©¤©¤ bootstrap.min.css ©¸©¤©¤ js ©¸©¤©¤ bootstrap.min.js |
Then we will create a new view from "admin/structure/views/add" to show latest added articles.
Here is a screenshot for our view initial settings:
After saving the view we will click on "Content: Title" and uncheck "Link to the Content", then add the "Body" field.
Here is a screenshot for the view final settings:
Views default templates are located under "/core/modules/views/templates/" folder.
Each view uses minimum of two templates:1
Each type of the view templates above can be overridden with a variety of names. The template name is a concatenation of (base template name, view machine name, view display type and view display id - separated by 2 hyphens "--").
The following are the possible template names sorted by precedence:
For example; If we want to override "views-view.html.twig" template for our view, the following template names are valid:
To build our version of bootstrap accordion, we will need to override "views-view-unformatted.html.twig" (because this is the style in use) and "views-view-fields.html.twig".
The easiest way to get started is to copy the templates from /core/modules/views/templates folder into our theme folder and then rename "views-view-unformatted.html.twig" to "views-view-unformatted--articles-accordion--page-1.html.twig" and "views-view-fields.html.twig" to "views-view-fields--articles-accordion--page.html.twig"
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | < div class = "panel-group" id = "accordion" role = "tablist" aria-multiselectable = "true" > {% for row in rows %} {% set row_classes = [ default_row_class ? 'views-row', 'panel', 'panel-default', ] %} < div {{="" row.attributes.addclass(row_classes)="" }}=""> {{ row.content }} </ div > {% endfor %} </ div > |
1 2 3 4 5 6 7 8 9 10 11 12 | < div class = "panel-heading" role = "tab" id = "heading-{{ row.index }}" > < h4 class = "panel-title" > < a role = "button" data-toggle = "collapse" data-parent = "#accordion" href = "#collapse-{{ row.index }}" aria-controls = "collapse-{{ row.index }}" aria-expanded = "true" > {{ fields.title.content }} </ a > </ h4 > </ div > < div id = "collapse-{{ row.index }}" aria-labelledby = "heading-{{ row.index }}" class = "panel-collapse collapse {% if row.index==0 %}in{% endif %}" role = "tabpanel" > < div class = "panel-body" > {{ fields.body.content }} </ div > </ div > |
This is how how our accordion looks like.