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');

}
?>

A use case for the above would be if you'd want to implement the theme path as a variable within a custom module. So using MYMODULE_preprocess_page with the above function, you could then render the path in your module's scripts file with jQuery as such:

$('#logo-img').attr('src', Drupal.settings.basePath + Drupal.settings.pathToTheme + '/images/logo-custom.png');

** note the use of Drupal.settings.basePath above, that's to render a forward slash at the beginning of the path.

This renders in HTML as:

<img id="logo-img" src="/sites/all/themes/mytheme/images/logo-custom.png" alt="My image alt tag">

Comments

Fleshgrinder’s picture

No PHP necessary:

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

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');

}
?>