kevinius
kevinius

Reputation: 4618

Override item-list.html.twig & time.html.twig inside a view

I've created a view that outputs a <ul> with a <time> element in each <li>. I need to convert the HTML list to a select.

So I did 2 things:

  1. Copied item-list.html.twig and changed <ul> to a <select>
  2. Copied time.html.twig and changed <time> to <option>

Although this works I need those 2 templates to be scoped to my view named: 'vcon-selection-table'. I tried many things but nothing works:

So the question is: What template name should I use to override the templates item-list.html.twig and time.html.twig inside my view?

Upvotes: 2

Views: 1623

Answers (1)

norman.lol
norman.lol

Reputation: 5374

Is the purpose of that view to only provide that <select> element and <option> elements? Then this really isn't the way to go. Don't build a form or form elements with Views.

You'd better provide a custom form or a custom item_list in a custom block. The block then can be placed where ever you need it. There are plenty of tutorials out there. Maybe take the following as a starting point: https://valuebound.com/resources/blog/creating-a-custom-form-in-a-block-in-two-steps-in-Drupal-8


Otherwise, if you really want to continue your road I think you have to simply preprocess the list and time fields to switch to a different template according your desired conditions. I strongly guess there is no option that a custom template for a field from a node in a view will automatically be taken into account by naming patterns. You have to add that template suggestion manually first.

Snippet to be placed in MYMODULE.module file or MYTHEME.theme file.

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYMODULE/MYTHEME_theme_suggestions_item_list_alter(array &$suggestions, array $variables) {

  // Use \Drupal::routeMatch() to get the current view ID or some other indicator.
  // Sample: Get the current view ID.
  $view_id = \Drupal::routeMatch()->getRouteObject()->getDefault('view_id');

  // Install Devel, Kint module, then uncomment the following line and flush caches to inspect the outcome.
  // ksm($view_id);

  // Add the template suggestion.
  // Add your template now under /templates/item-list--VIEWID.html.twig
  if (!empty($view_id)) {
    $suggestions[] = 'item_list__' . $view_id;
  }
}

Downside of this approach is that this would trigger all item_lists that live on that exact page/view to take this template. You could fine-grain your templating much better with a custom module and a custom item_list and/or form.

Alternatively you can also move the logic to the date field and a custom view mode and an extra template for that. Then at least it stays where it belongs to.


To enable Twig debugging and getting the built-in template suggestions printed as HTML comments follow this article: https://www.drupal.org/docs/8/theming/twig/debugging-twig-templates

Upvotes: 1

Related Questions