0

I want to print the creation date of nodes of type article between two fields. I know you can do this with Display Suite, but I don't want to install the module only for this functionality. My only idea is to put an if condition into the for loop of field.html.twig to print the date after a certain field occurs, but I wonder if there is a better solution.

1

Yes, you would need a module like Display Suite only if you want to do this in UI. For a solution in code you can add extra information to the render array $variables['content'] in a preprocess hook:

mytheme.theme:

/**
 * Implements hook_preprocess_HOOK() for node templates.
 */
function mytheme_preprocess_node(&$variables) {

  $node = $variables['node'];

  if ($node->getType() == 'article') {
    $variables['content']['created'] = [
      '#markup' => t('<p>Node created: @created</p>', [
        '@created' => format_date($node->getCreatedTime(), 'medium'),
      ]),
      '#weight' => '5',
    ];
  }

}

Adjust weight to position it between the two fields.

2
  • Ok, one problem I just noticed: the markup is inserted in every view mode... – 0711master Feb 23 '18 at 0:59
  • 1
    You can check the view mode in $variables['view_mode'] – 4k4 Feb 23 '18 at 7:19

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.