Drupal Language based CSS file on Multilingual Site - Alternate Solutions?

Drupal 8 uses libraries theme.libraries.yml

 globle-styling:
   version: VERSION
   css:
     theme:
       css/style.css: {}
 style-engb:
    version: VERSION
    css:
      theme:
         css/style-gb.css: {}

Solution: 1) html.html.twig

 {% if html_attributes['lang'] == 'en' %}

    {{ attach_library('THEME_NAME/globle-styling') }}

  {% else if html_attributes['lang'] == 'en-gb' %}

    {{ attach_library('THEME_NAME/style-engb') }}

  {% endif %}

Solution: 2) THEME_NAME.theme

 function THEME_NAME_preprocess_page (&$variables) {

    // Get current language code

    $language = \Drupal::languageManager()->getCurrentLanguage()->getId();

    if($language == 'en') {

      $variables['#attached']['library'][] = 'THEME_NAME/globle-styling';

    } else if($language == 'en-gb') {

      $variables['#attached']['library'][] = 'THEME_NAME/style-engb';

    }

  }

Solution: 3) Alternative, We should add it to info.yml file and alter the css using this hook_css_alter() function.

function THEME_NAME_css_alter (&$css, \Drupal\Core\Asset\AttachedAssetsInterface $assets) {

  // Get current language code

  $language = \Drupal::languageManager()->getCurrentLanguage()->getId();

  // Change theme style sheets being loaded based on current language.

  if($language == 'en') {

    unset($css[drupal_get_path('theme', 'THEME_NAME') . '/css/style-gb.css']);

  } else if($language == 'en-gb') {

    unset($css[drupal_get_path('theme', 'THEME_NAME') . '/css/style.css']);

  }

}

Solution: 4) THEME_NAME.theme

function THEME_NAME_preprocess_html (&$variables) {

  // Load specific library for pages with html attribute of RTL

  $language = \Drupal::languageManager()->getCurrentLanguage()->getId();

  if($language == 'en') {

    $variables['#attached']['library'][] = 'THEME_NAME/globle-styling';

  } else if($language == 'en-gb') {

    $variables['#attached']['library'][] = 'THEME_NAME/style-engb';

  }

}

Solution: 5) Also, There is a hook that can be used to alter libraries called: hook_library_info_alter().

Clear the drupal caches.

Comments

Brilliant, thank you!

PS: Check the example library names you used in Solution 1. They are different than the other examples.

Thanks man, that was very helpful :)
I choose cicr_preprocess_html to add a entire library a remove another one to manage arabic language righttoleft.

This solution was what I was looking for. Thanks for the great tutorial.

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
5 + 14 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.