2

So there was already the same question for D7 (How do I render a field on a node twice with two different field formatters?) but now i wanted to know how to do this in d8.

Maybe this helps a little bit, but i could not get it working. Rendering arbitrary field values without a parent entity in Drupal 8

4

So in drupal 7 you could use:

$output = field_view_field('node', $node, 'field_foo', array('type' => 'some_formatter', 'settings' => array(...), $langcode));

to render a field with a specific formatter. The drupal 8 the equivalent is:

$output = $node->field_foo->view(array('type' => 'some_formatter', 'settings' => array(...)));

source: Change record

Now to render the fields I would create a preprocess for a node

function HOOK_preprocess_node(&$variables) {
  $variables['my_field_formatter1'] = $node->field_foo->view(array('type' => 'some_formatter', 'settings' => array(...)));
  $variables['my_field_formatter2'] = $node->field_foo->view(array('type' => 'some_formatter', 'settings' => array(...)));
}

and then print my_field_formatter1 and my_field_formatter2 in your twig template for the node.

2
  • 1
    Thanks, this works. Don't know why but the preprocessor only works in a module not in a theme.
    – kitikonti
    Sep 21 '16 at 18:38
  • 1
    Glad to hear. Hmm... weird I think it should also be working in a theme. Not sure
    – Denchev
    Sep 22 '16 at 3:41
1

There is a module for that™️: Use Display Field Copy

From the module page:

Display Field Copy provides the ability to make a display copy of a field with Display Suite. The copy of the field can use a different formatter (with different config) than the single field that is currently available in core.

For instance, if a site has a single entity reference field and the display needs the list rendered on the page twice (once as a rendered entity and once as a list of links). This module could be used to create a copy of the field and apply a different formatter to it.

This module does not have a copy limit. Theoretically, an unlimited number of copies could be created. It should work for any field that has at least one formatter available.

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.