Best practice to alter the attributes variable in a Drupal 8 Twig template 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:

&lt;ul class="nav navbar-nav"&gt;...&lt;/ul&gt;


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:

&lt;ul{{ attributes}}&gt;


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(&amp;$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 &lt;ul&gt; to:

&lt;ul{{ attributes.addClass(['nav', 'navbar-nav']) }}&gt;


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

What do you think?
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.