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?

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.

| improve this answer | |
  • I think it would be better to frame the date with tag to simplify setting of CSS styles. – Yakimkin Roman Dec 28 '16 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 '16 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 '16 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 '16 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 '17 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.

| improve this answer | |

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.