Community Documentation

Pass the theme path to javascript

Last updated February 3, 2012. Created by waako on February 3, 2012.
Log in to edit this page.

Description

This extends Drupal.settings allowing you to get the theme path in a javascript file

Steps

Add a preprocess function to your theme's template.php
Using drupal_add_js we extend Drupal.settings in order to make it a variable that returns the path to the theme

p.s. don't copy the php tags into template.php just what's inside.

<?php
function theme_preprocess_page(&$variables) {

drupal_add_js('jQuery.extend(Drupal.settings, { "pathToTheme": "' . path_to_theme() . '" });', 'inline');

}
?>

Comments

Another way could be like

Another way could be like this;

<?php
 
global $theme_path;
 
drupal_add_js(array('pathToTheme' => array('pathToTheme' => $theme_path)), 'setting');
?>

then in jquery call it like this;
Drupal.settings.pathToTheme.pathToTheme;

Another alternative

No PHP necessary:

Drupal.behaviors.yourThemeName = function (context) {
  var pathToTheme = Drupal.settings.basePath + "sites/all/themes/" + Drupal.settings.ajaxPageState.theme;
};

What if you don't know if

What if you don't know if your theme is under sites/all or sites/example.com ?

Function add /node/.. before path

I have changed the function a bit to solve a problem that adds /node/{path_to_theme}/

<?php
function theme_preprocess_page(&$variables) {

   
drupal_add_js('jQuery.extend(Drupal.settings, { "pathToTheme": "/' . path_to_theme() . '" });', 'inline');

}
?>

Page status

No known problems

Log in to edit this page

About this page

Drupal version
Drupal 7.x
Audience
Designers/themers
Level
Advanced
Keywords
javascript, template, theming

Theming Guide

Drupal’s online documentation is © 2000-2013 by the individual contributors and can be used in accordance with the Creative Commons License, Attribution-ShareAlike 2.0. PHP code is distributed under the GNU General Public License. Comments on documentation pages are used to improve content and then deleted.