I created two variables for use in my theme's page templates. I used variables because I wanted that value to be flexible.

function mytheme_preprocess_page(&$variables) {
  $variables['var1'] = 'value1';
  $variables['var2'] = 'value2';

Without creating a new page.html.twig template, I want to choose new variables in mymodule. Like, maybe...

function mymodule_preprocess_page(&$variables) {
  $variables['var1'] = 'newvalue1';
  $variables['var2'] = 'newvalue2';

This isn't working. I have a feeling it's because themes get priority? Any ideas?

Edit: I should clarify. How do I do this?

  • Themes do get priority as it is the last in line. – Kevin Oct 31 '19 at 14:49
  • How can I make the module take priority in this case? – Sarah C Oct 31 '19 at 14:53
  • 3
    What's the point in having those lines in the theme, if the module takes precedence? Why not remove them? (If they supply a default, you could check whether there's already a value rather than setting unconditionally). – Alfred Armstrong Oct 31 '19 at 15:02
  • Most of our sites built on this platform using a basetheme/sub-theme will need the same values. But from time to time we'll need a one-off site that has a custom module to do this and other site-specific things. So all of our sites will share the default values, but sometimes we'll need to override them. – Sarah C Oct 31 '19 at 15:08

Taking the lead from @Alfred Armstrong above and my colleague, this ended up working!

In mytheme.theme

function mytheme_preprocess_page(&$variables) {
  if(!isset($variables['var1'])) {
    $variables['var1'] = 'defaultvalue1';

In mymodule.module

function mymodule_preprocess_page(&$variables) {
  $variables['var1'] = 'myvalue1';
  • 1
    In php 7 you can do this in one line using the null coalescing operator "??". Try $variables['var1'] = $variables['var1'] ?? 'default'; – Charles Bamford Oct 31 '19 at 15:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.