0

I have a content type (Press releases) with three fields: field_date, field_location, and body.

I am trying to create a template override for this content type based on this design.

screenshot

As you can see in the image, the date and location fields are appended to the body field.

I have tried adding all the fields in a single <div> and setting its display property to inline, but nothing has happened.

This is the code from the template override.

<div class="press-releases-body">
  {{content.field_release_date}}
  {{content.field_location}}
  {{ content.body }}
</div>
1
  • 2
    What template is this? If the layout is affected by CSS/HTML you don't want, it's likely that your template is picking up other templates "down the chain" (for example, a node type template is pulling in field templates). Oct 21, 2022 at 15:15

2 Answers 2

4

For a formatted text field I would append the field data in a preprocess hook so that you can add the text within the enclosing field template and also remove the <p> tag Ckeditor adds automatically to the content of the field:

function mytheme_preprocess_node__press_releases(&$variables) {
  /** @var \Drupal\node\NodeInterface $node */
  $node = $variables['node'];
  if (isset($variables['content']['body'][0])) {
    $body = $variables['content']['body'][0]['#text'];
    $body = preg_replace(['#^<p>#', '#</p>$#'], '', $body);
    $date = $node->field_date->date ? $node->field_date->date->format('Y-m-d H:i:s') : '';
    $location = $node->field_location->value;
    $body = $date . ' - ' . $location . ' - ' . $body;
    $variables['content']['body'][0]['#text'] = $body;
  }
}

Then you don't need to configure the two appended fields in the display settings and it's not necessary to change the twig template.

3
  • the above solution is working for me
    – Sam Bara
    Oct 25, 2022 at 8:35
  • how to implement an empty check for the location and date field before running this code
    – Sam Bara
    Nov 2, 2022 at 15:48
  • I've already included a check for the date field to avoid a PHP error trying to run a method on NULL . The location value property returns NULL without error. For further logic you can then test both variables in if (!empty(...)) {
    – 4uk4
    Nov 2, 2022 at 16:43
1

Patrick Kenny is, most probably, right about templates "down the chain".

Copy your_site_directory/sites/default/default.services.yml

as your_site_directory/sites/default/services.yml

and modify it to enable twig debug:

parameters:
  twig.config:
    debug: true

Clear the caches and inspect what templates you should target.

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.