Drupal Answers is a question and answer site for Drupal developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question

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.

share|improve this answer
    
I think it would be better to frame the date with tag to simplify setting of CSS styles. – Yakimkin Roman 3 hours ago
    
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 3 hours ago

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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