Flipping the Web..

You are here

Create a bidirectional Drupal theme using Foundation

Adding RTL support to a drupal theme can be time consuming. Also maintaining it is not easy. I've figured out a way to have a bidirectional drupal theme, by using the power of CSS preprocessors and the amazing framework "Foundation".

Let's say your theme loads a theme.css file. If you're page language's direction is rtl, drupal looks for theme-rtl.css in the same place and loads if afterhy the original one. So to "rtl" your theme, you need to add that theme-rtl.css file and override in it all of the directional rules from theme.css(check the 3rd method in this tutorial).

Although it seems straight forward and easy(it is), maintaining large themes with multiple CSS files can be overwhelming and time consuming. It also becomes almost impossible if you're using a CSS preprocessor with many .scss or .less files everywhere.

Solution

Use the power of CSS preprocessor to do the work for you. You create one file, and compiler mirrors the -rtl.css for you.

Find a framework that supports RTL

I chose "Foundation" because it's responsive, very easy to use/learn and it comes with native RTL support! Their drupal base theme is "ZURB Foundation"2.

In your newly created subtheme, you'll find the main scss file that will generate your CSS file. In our case it'll be "myrtltheme.scss". You'll notice that before loading the framework's scss files, "base/init" is imported which can hold global Zurb Foundation variable overrides.

@import "base/init";

2.1 Copy "myrtltheme.scss" to "myrtltheme-rtl.scss" and replace that import with:

@import "base/init-rtl";

2.2 Copy "base/_init.scss" to "base/_init-rtl.scss". Foundation has 4 variables to control text direction: "$text-direction", "$opposite-direction", "$default-float" and "$last-child-float". So our new _init-rtl.scss file will be like:

This way when you run grunt or grunt watch, a mirrored clone of your myrtltheme.css will be generated at myrtltheme-rtl.css.

Step 4: Start theming

Start styling your theme as you like, while keeping in mind that whenever a directional value is used, use the variables you had to override in step 3. Below is an example of floating some element to the left with margin-left : 1em:

.element{ float:$default-float; margin-#{$default-float} : 1em; }

This will be in myrtltheme.css

.element{ float: left; margin-left:1em;}

and in myrtltheme-rtl.css:

.element{ float: right; margin-right:1em;}

Step 5: Exclude the main .css in ltr pages

Drupal loads the .css file by default and adds the -rtl.css files if we're in rtl mode. So by default, -rtl.css files should only hold directional overrides when theming in Drupal. Since this is not the case here(-rtl.css file holds everything), loading myrtltheme.css and myrtltheme-rtl.css would be a waste of bandwidth and time(to load). So we add this small hook to "template.php" to remove the .css file from the links when building the page.