2

I'm using the Basic theme and want to show the article date before the title. The problem is, that {{ date }} is only available in node.html.twig, whereas the title is created in page-tite.html.twig.

How can I place the article date before the title?

2 Answers 2

3

You can do this by implementing template_preprocess_page_title() hook in your Theme (THEME_NAME.theme). Check example below:

/**
 * Implements hook_preprocess_HOOK() for page templates.
 */
function [THEME_NAME]_preprocess_page_title(&$variables) {
  // Check if page is node page, and is instance of Node.
  if (($node = \Drupal::routeMatch()->getParameter('node')) && ($node instanceof \Drupal\node\NodeInterface)) {
    // Get created time of Node and convert to human readable, and append Node title.
    $variables['title'] = '<span class="created-date">' . date("d m Y", $node->created->getValue()[0]['value']) . "</span> " . $node->getTitle();
  }
}

Similar question is answered by @Linus's here.

5
  • I think it would be better to frame the date with tag to simplify setting of CSS styles. Dec 28, 2016 at 5:35
  • Yes @YakimkinRoman, you're write. that would help style date differently. And since its a custom code we can alter it to match our needs. Thanks for pointing out, I'll update my answer with it.
    – Yogesh
    Dec 28, 2016 at 5:37
  • Thank you! In the meantine I found the other answer too and combined it with another answer in the same thread:
    – 0711master
    Dec 29, 2016 at 12:54
  • function THEME_preprocess_page(&$variables) { if ($node = \Drupal::request()->attributes->get('node')) { $variables['date_before'] = \Drupal::service('date.formatter')->format($variables['node']->getCreatedTime(), 'long_date_without_time'); } }
    – 0711master
    Dec 29, 2016 at 12:55
  • I changed the if condition $node = Drupal::request()->attributes->get('node') back to your solution, because otherwise getCreatedTime() is throwing some null error when a page is restricted by Content Access module for whatever reason...
    – 0711master
    Jan 5, 2017 at 10:45
0

I think, in Drupal 8 it would be not bad solution to define new block for it. In this block one get value of date field and place this block before block with node title.

How to create block programmatically, you can see in a example of module Examples.

Your Answer

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

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