3

Is it possible via Twig to output a field's value, that uses the fields formatter. I would like to display a file field two different ways in the same twig file. The first will be a link to the file with a label to the left. The second will be the SOLR Extract text from the file, with a label on the left.

Here are the formatters I am talking about. Drupal 8 entity display management enter image description here

As shown in the second image, there are multiple options for how to display the field. Is there a way in Twig to do something like the following.

{{ content.field_name.FORMATTER_NAME_HERE }} or
{{ content.field_name[0].value | FORMATTER_NAME_HERE }}

I would like to use the URL to file and Text extracted from attachment formatters.

2 Answers 2

4

There's no out of the box way to display a field in twig with two different formatters. But it can be done with a hook in a custom module.

You can repurpose a field in hook_entity_view or hook_ENTITY_TYPE_view().

Here's an example:

function mymodule_entity_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {

  if ($entity->getEntityTypeId() == 'node' && $entity->bundle() == 'article' && $view_mode == 'teaser') {   
    $settings = [
      'type' => 'pdf_special_formatter',
      'settings' => $build['field_pdf']['#items']->getSettings(),
    ];
    $build['pdf_alternate_display'] = $build['field_pdf']['#items']->view($settings);

  }  
}

Note that the settings may need to be altered before sending to another field formatter. You'll have to look at that field formatter for the required settings.

1
  • While this looks like the way to go... I can't get the field formatter Text extracted from attachment to show any content. However, when changing my view from Rendered content to Fields I can use Search: Excerpt and that will show it. Due to this I am going to look into leveraging views with Fields instead. I will post back progress. Commented Aug 23, 2017 at 19:09
2

Technically it is possible. Field items have a public view method that accepts either view mode or field formatter. Unfortunately that method is not allowed by default Twig sandbox policy in Drupal. You need to override it in your settings.php file as described here.

{{ node.field_image.view({type: 'image', settings: {image_style: 'large'}}) }}

An alternative approach could be using Twig Tweak module which provides a wrapper around this method.

{{ node.field_image|view({type: 'image', settings: {image_style: 'large'}}) }}

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.