drupal-themingdrupal-8drupal-templates

drupal 8 show field twice


I created a custom bundle (content type) and I've created fields

One of those field is a file type field, is a video file, stored in the private storage. I installed the videojs module to allow to watch the video.

I need to show this field twice in the node page. One in the generic file formatter that allows the user to download the file, and I also need to play the video. I decided to set up as generic file formatter and customize the twig template to show again with the video player.

I achieve to show twice with the settings formatter (generic file) with this code in the node--mybundle--full.html.twig template

{{ content.field_sd_video }}

I thought it would be something easy like field+formatter:

{{ content.field_sd_video|videojs_formatter }}

But I can't find what is the simple way to achieve this. May be it's necesary more a tricky way ?


Solution

  • I finally found the solution, I put this code in preprocess node function. It has to be easy, but not easy to know how ;)

    function mytheme_preprocess_node(&$variables) {
    
         $variables['video_caption'] = $variables['node']->get('field_video')
             ->view(array(
                'label' => 'hidden',
                'type' => 'videojs_player_list'
            ));
    }
    

    and I only has to add this line in twig file:

    {{ video_caption }}
    

    in my case node--mybundle--full.html.twig template

    For those arrive here looking for something similar I was inspired by Twig Recipes on page 41
    It was usefull for me Twig debugging. Playing with kint and node variable and the classes used to wrap the information. Then I found that the field comes with [FileFieldItemList] and then I found the view method that uses [EntityViewBuilderInterface]