2

In Drupal 8, I'm trying to change part of a twig template according to time of day.

For instance, if in one of my twig templates I have:

<img src="img_during_the_day.jpg"/>

Where and what do I need to change to have it produce

<img src="img_during_the_day.jpg"/>
<!-- or -->
<img src="img_during_the_night.jpg"/>

according to server time?

I was thinking of doing it passing a variable to my twig template and then something like:

{{ if (variable == 'day') }}
    <img src="img_during_the_day.jpg"/>
{{ else }}
    <img src="img_during_the_night.jpg"/>
{{ endif }}

But I don't know how to pass a $variable to the template. Also, if I were to do this in a module, what hook would I have to alter to achieve this?

The idea would be to use PHP's date object to find out the current time to then change the value of a certain $variable in a hook, and said variable would be available to work in twig with in the above pseudo-syntax.

Can anyone share some pointers on where to begin?

1 Answer 1

2

You can define new variables in the array $variables in preprocess.

Assuming this is the page template:

modules/mymodule/mymodule.module:

function mymodule_preprocess_page(&$variables) {
  if ( ... ) {
    $variables['daynight'] = 'day';
  }
  else {
    $variables['daynight'] = 'night';
  }
}

Then use the variable in your twig code:

{{ if (daynight == 'day') }}
    <img src="img_during_the_day.jpg"/>
{{ else }}
    <img src="img_during_the_night.jpg"/>
{{ endif }}

Or shorter:

<img src="img_during_the_{{ daynight }}.jpg"/>

You will get some problems with caching. In drupal and in proxies and browsers. So this is probably not a server but a client side solution.

3
  • +1 for factoring the caching issues, I totally forgot about that. Guess I'll figure something out with JS, then.
    – Joum
    Jul 21, 2016 at 14:54
  • But, on the other hand, can't caching be disabled for a certain page? At least at (my) server level?
    – Joum
    Jul 21, 2016 at 14:56
  • Nearly positive you can update $variables['#cache'] in the preprocess to add any ages/contexts you need.
    – mpdonadio
    Jul 21, 2016 at 15:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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