Theming in JavaScript
Drupal provides a theming mechanism for JavaScript code in a similar manner to the way theming works within the rest of Drupal. This lets themes customize the markup generated by JavaScript.
Modules provide theme functions for their markup. For example, the following code provides the theme function powered which displays a "powered by Drupal" icon:
Drupal.theme.powered = (color, height, width) =>
`<img src="/misc/powered-${color}-${height}x${width}.png" />`;
When a module wants to insert the markup it might do this:
document.querySelector('.footer')
.insertAdjacentHTML('beforeend', Drupal.theme('powered', 'black', 135, 42));That will find any elements with the class footer and place an image in them with the following markup:
<img src="http://drupal.org/misc/powered-black-135x42.png" />
When a theme wants to provide different markup it can do so by providing its own theme function. Continuing our example, the following function overrides an existing JavaScript theme function when added by a theme.
Drupal.theme.powered = (color, height, width) =>
`<div class="powered-${color}-${height}x${width}"></div>`;
If you now try this again:
document.querySelector('.footer')
.insertAdjacentHTML('beforeend', Drupal.theme('powered', 'black', 135, 42));
You'll get:
<div class="powered-black-135x42"></div>
JavaScript theme functions are entirely free in their return value. They can vary from simple strings to complex data types like objects, arrays, and jQuery elements. Refer to the original (default) theme function to see what your custom theme function should return.
Help improve this page
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion
Still on Drupal 7? Security support for Drupal 7 ended on 5 January 2025. Please visit our Drupal 7 End of Life resources page to review all of your options.