Skip to main content

Drupal 8 - styling local task tabs with Bootstrap 4

Styling navigation tabs with Bootstrap 4, for example on node page:

menu local tabs with Bootstrap 4 screenshot

Replace scriptun with your theme name and override needed file in your theme. For main list we need additional nav and nav-tabs classes:

{# /themes/scriptun/templates/navigation/menu-local-tasks.html.twig #}

{#
/**
 * @file
 * Theme override to display primary and secondary local tasks.
 *
 * Available variables:
 * - primary: HTML list items representing primary tasks.
 * - secondary: HTML list items representing primary tasks.
 *
 * Each item in these variables (primary and secondary) can be individually
 * themed in menu-local-task.html.twig.
 */
#}
{% if primary %}
    <div class="container">
        <h2 class="visually-hidden">{{ 'Primary tabs'|t }}</h2>
        <ul class="nav nav-tabs nav-tabs-admin">{{ primary }}</ul>
    </div>
{% endif %}
{% if secondary %}
    <div class="container">
        <h2 class="visually-hidden">{{ 'Secondary tabs'|t }}</h2>
        <ul>{{ secondary }}</ul>
    </div>
{% endif %}

Every list element in tabs need additional class nav-item:

{# /themes/scriptun/templates/navigation/menu-local-task.html.twig #}

{#
/**
 * @file
 * Theme override for a local task link.
 *
 * Available variables:
 * - attributes: HTML attributes for the wrapper element.
 * - is_active: Whether the task item is an active tab.
 * - link: A rendered link element.
 *
 * Note: This template renders the content for each task item in
 * menu-local-tasks.html.twig.
 *
 * @see template_preprocess_menu_local_task()
 */
#}
<li{{ attributes.addClass('nav-item') }}>{{ link }}</li>

Links also need additional class nav-link and active instead of default is-active:

// /themes/scriptun/scriptun.theme

function scriptun_preprocess_menu_local_task(&$variables) {
  $class = array('nav-link');
  if($variables['element']["#active"])
  {
    $class[] = 'active';
  }
  $variables['element']['#link']['url']->setOption('attributes', array('class' => $class));
}

Now you should see Bootstrap styled tabs on every page with local tasks (node page, user page). 

Add new comment

CAPTCHA

This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.

Comments

Pita (not verified)

Thanks for posting! Just what I was looking for :)

Viktor (not verified)

It is very helpful article. Could you also move theming logic in the template?

Scriptun

Thanks. Moving logic to theme? All in twig template!? I don't think it's possible. You need to change active class behavior and it's not possible in twig file. There is only "link" variable available with whole <a> element. Workaround can be to define styles for is-active class instead of using default bootstrap .active

We use cookies on our website to enhance your user experience. We also use Google analytics and ads.

Click here to read more I've read it