Tuesday, 12 January 2016

Drupal 7 - Switch CSS file based on Language

I have the need to load a different css file depending on the language of a drupal 7 site.  This is the hook that I created. hope it helps people.

function hook_css_alter(&$css) {
  global $language;
  $theme_path = "sites/all/themes/mytheme";
  if (file_exists(__DIR__ . "/css/styles-" . $language->language . ".css")) {
    $newKey = $theme_path."/css/styles-" . $language->language . ".css";
    $oldKey = $theme_path."/css/styles.css";
    $css[$newKey] = $css[$oldKey];
    $css[$newKey]['data'] = $newKey;
    $css = array_diff_key($css, Array($oldKey => 1));

The theme.info file would have a line like 

stylesheets[all][] = css/styles.css

This line is removed and replaced with a language specific css file  if a language specific version exists.  For example if you have a multilingual site with french the $language->language value might be for example "fr" in which case the file that will be loaded will be styles-fr.css instead of styles.css

Using SASS allows the building and maintaining of site wide css files.

No comments:

Post a Comment