4

I have to change the markup and I have to add CSS classes to themes/classy/templates/dataset/item-list.html.twig. But only for a specific item-list.html.twig in a specific block.

How do I create a preprocess function, which create a template suggestion for this item-list.html.twig? So I am able to use e.g. item-list-facets.html.twig?

1
  • You have been asking this already in drupal.stackexchange.com/questions/227668/…, and I don't know how to help you more without just writing down the code for you. You need to inspect the data structures you get and then do something conditionally based on that. Or, as I suggested already over there, request a more specific theme (suggestion) from the module developers
    – Berdir
    Feb 10, 2017 at 20:54

2 Answers 2

4

I think it's better to use hook__theme_suggestions_HOOK_alter:

Something like this:

 /**
 * Implements hook__theme_suggestions_HOOK_alter().
 */
function MYTHEME_theme_suggestions_item_list_alter(&$suggestions, $variables) {
  $suggestions[] = 'item_list__' . str_replace('-','_',$variables["attributes"]["id"]);
}

Just make sure that in your suggestions name you use _ instead of -, otherwise you will get suggestions in the debug, but Drupal won't use it.

-1

If its a class you might not need to have a separate twig file, but can simply add a class in your preprocess.

/**
 * Implements hook_preprocess_HOOK().
 */
function MYTHEME_preprocess_item_list($variables) {
  // conditional class
  $variables['custom-class'] = _some_function_to_return_class();
}

Copy the item-list.html.twig to your custom theme folder, and use the class.

4
  • But then this class is added to ALL item-list.html.twig files in my subtheme? I want to create a separate item-list.html.twig file e.g. item-list-facets.html.twig. Or can I do it with twig, inside my custom theme's item-list.html.twig ?
    – meez
    Feb 10, 2017 at 7:06
  • _some_function_to_return_class(); should be responsible to provide unique class based on field name etc. you can do it either way, with tem-list-facets.html.twig or item-list.html.twig.
    – arpitr
    Feb 10, 2017 at 7:28
  • Thanks. Sorry can you provide me with an example? I don't understand. What do you mean with _some_function_to_return_class(); How do I wright the function to return class?
    – meez
    Feb 10, 2017 at 9:30
  • in <li class="facet-item"> I have to add a custom class, so I have e.g. <li class="facet-item custom-class">. How do I have to do this?
    – meez
    Feb 10, 2017 at 19:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.