I'm making a custom theme, and I just want to include this in my twig file.
<?php echo date("l H:i"); ?>
Do I need make a twig extension? How can I do it?
Drupal Answers is a question and answer site for Drupal developers and administrators. It only takes a minute to sign up.
Sign up to join this communityOne way to do it would be to add the variable in a preprocess function, and print that out in the chosen twig template as {{ your_variable }}
.
function yourtheme_preprocess_page(&$variables) {
$variables['your_variable'] = \Drupal::get('date.formatter')->format(args);
}
I'm not sure where you are doing this, so your use case could be _page, _node, _html, _block for the preprocessor.
Since you are not passing a timestamp to date, it will assume current time and print that. If that is your intent, you should consider that when caching mechanisms are enabled, it won't show the current time anymore, and you should consider a Javascript based solution to keep that accurate (something like momentjs?). Again, don't know your full use case here.
edit: see https://api.drupal.org/api/drupal/core%21includes%21common.inc/function/format_date/8
\Drupal::get('date.formatter')
, and then use the methods on that service (usually just ->format()
. This lets you use your predefined formats, and also handle localization properly. Two, since your output now is dependent on the date, you need to set a max age (probably 0) to $variables['#cache']
. See drupal.org/developing/api/8/render/arrays/cacheability for more info.
{{ "now"|date("l H:i") }}
Welcome to drupal.stackexchange!