5

I'm creating a custom Drupal 8 theme based on Bootstrap. (NOTE. I'm aware of https://www.drupal.org/project/bootstrap, I just want some practice.)

More often than not, I find myself adding Bootstrap classes to the existing Drupal classes via the Attribute object already available in the template.

For instance, in Bootstrap, the main navigation menu looks like this:

<ul class="nav navbar-nav">...</ul>

What is the best practice is to add the nav navbar-nav classes to Drupal's menu.html.twig template? This template already contains the following line:

<ul{{ attributes}}>

1) Add the classes with a preprocess function?

I could add the following function to my MYTHEME.theme file to alter the attributes variable before it's passed to the template:

function MYTHEME_preprocess_menu(&$variables) {
  if ($variables['menu_name'] == 'main') {
    $variables['attributes']['class'][] = 'nav';
    $variables['attributes']['class'][] = 'navbar-nav';
  }
}

2) Add the classes directly inside the Twig template?

First, I'd create a template named menu--main.html.twig to override only Drupal's main menu.

Then, I'd alter the line with the <ul> to:

<ul{{ attributes.addClass(['nav', 'navbar-nav']) }}>

I find #2 a little less clean but it keeps all the markup in the same place.

What do you think?

3

If it is your theme then I would do it in a template. Drupal Core converted a lot of preprocess/template to work like that, e.g. the node template.

The advantage is that everything is together as you said and it's a lot easier change it later.

Also if you're a module that defines a template, then someone can just copy that, adjust it and have full control over the classes.

| improve this answer | |
  • I am indeed creating a theme. I tend to agree with you, but even if I put my code in the THEME.theme file (in a preprocess function), it would still be packaged with the theme, not in a module. – AngularChef Jan 15 '16 at 8:57
  • I agree with Berdir. A good example is the classy theme in core, which brings back some of the drupal 7 divs and classes. This theme only uses twig templates, no php: /core/themes/classy – 4k4 Jan 15 '16 at 9:08

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