7

I have a multi language website, one of languages is a RTL language, in Drupal 7 I put my CSS in style.css and RTL CSS to style-rtl.css and by default drupal also load style-rtl.css file, Now in Drupal 8 ,I have a multi language theme, how can I tell Drupal to load my RTL style in RTL language?

update I found this link but I am not sure about that because I have a CSS file with almost 1400 lines, I should put [dir="rtl"] before all of any selector ? !!!

7

Drupal 8 uses libraries, and you can load these in templates. One way of achieving language direction dependant libraries would be to use the html_attributes['dir'] variable in html.html.twig and load different libraries depending on the value:

{% if html_attributes['dir'] == 'ltr' %}
  {{ attach_library('your_theme_name/styles') }}
{% elseif html_attributes['dir'] == 'rtl' %}
  {{ attach_library('your_theme_name/styles_rtl') }}
{%- endif -%}

Set up a couple of libraries:

styles:
  version: 8.x-1.0
  css:
    theme:
      css/styles.css: {}

styles_rtl:
  version: 8.x-1.0
  css:
    theme:
      css/styles-rtl.css: {}
1

For those who are looking for an alternative solution:

You can also define a new library in libraries.yml file of your theme and point that library to use a certain CSS or JS or whatever you need.

Next step is to use a preprocess such as theme preprocess to tell Drupal8 to use that library in a specific condition.

Example: Defining new library beneath your default one in themename.libraries.yml

rtl:
  version: VERSION
  css:
    theme:
      assets/css/themename.style-rtl.css: {}

Next you can detect the current direction of your pages with a preprocess in themename.theme file:

function themename_preprocess_html (&$variables) {
    // Load specific library for pages with html attribute of RTL
    if ($variables['html_attributes']['dir'] == 'rtl') {
          $variables['#attached']['library'][] = 'themename/rtl';
    }
}

Clear the cache and you are good to go

  • Thanks, this worked for me. Just wanted to point out that adding the library to the info.yml file will make it load in every page which is not what we need for multilingual sites. – Achraf JEDAY Aug 9 '17 at 20:21
  • Sure thing but I'm not saying that you should add it to info.yml file but libraries file, you can include a library based on your need in twig as well, so it's up to you – Sohail Nov 2 '17 at 9:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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