On my Drupal 8 site, I want to put a code in the user's template to display his status (online, absent or offline).
I want to do this only with TWIG, without creating a custom module.
In the conditions, how then to calculate the last access of the user and the current time ?
Here is what I want to put in condition :
If the user has accessed the site for less than 15 minutes, he is online.
Otherwise, if the user has accessed the site for more than 15 minutes and less than 30 minutes, he is absent.
Otherwise it is offline.
user--full.html.twig :
{% if ??? %}
<div class="mt-2 text-center font-weight-bold font-italic text-success">
<i class="fa fa-circle fa-lg"></i> Online
</div>
{% elseif ??? %}
<div class="mt-2 text-center font-weight-bold font-italic text-warning">
<i class="fa fa-circle fa-lg"></i> Absent
</div>
{% else %}
<div class="mt-2 text-center font-weight-bold font-italic text-danger">
<i class="fa fa-circle fa-lg"></i> Offline
</div>
{% endif %}
UPDATE 1
The following code displays the "timestamp" of the last access :
{{ user.access.value }}
The following code displays the current "timestamp" :
{{ 'now'|date('U') }}
How to calculate and display the correct status ?
https://twig.symfony.com/doc/3.x/templates.html#math
UPDATE 2
The answer works, here is the result of the operation :
{{ date().timestamp }}
{{ user.access.value }}
{{ (date().timestamp - user.access.value) }}
But there is a problem, if I reload the page, the number never changes. To update it I must empty the cache.
{% if (date().timestamp - user.access.value) < 900 %}
<div class="mt-2 text-center font-weight-bold font-italic text-success">
<i class="fa fa-circle fa-lg"></i> Online
</div>
{% elseif (date().timestamp - user.access.value) < 1800 %}
<div class="mt-2 text-center font-weight-bold font-italic text-warning">
<i class="fa fa-circle fa-lg"></i> Absent
</div>
{% else %}
<div class="mt-2 text-center font-weight-bold font-italic text-danger">
<i class="fa fa-circle fa-lg"></i> Offline
</div>
{% endif %}
UPDATE 3
Currently I am using a view with EVA and the view cache disabled.
I want to reproduce the same behavior directly in TWIG. The response code works, but I want to disable the cache for the user status element (online, absent, offline).
I added the code below in the bootstrap_subtheme_front_office_old.theme
file of my sub-theme.
It is not correct, how to target only the status code ?
/**
* User online status.
*/
function bootstrap_subtheme_front_office_old_preprocess_block(&$variables) {
if ($variables['plugin_id'] == 'block_id') {
$variables['#cache']['max-age'] = 0;
}
}
$variables['#cache']['max-age'] = 0;
- 2pha