1

I have a content type (exercises) which contains a text field (field_path). In this text field I have a path to a video file. I would like to retrieve the value of this field in theme_preprocess_node and depending on the file type (mp4, webm, avi, etc...) adapt the html formatting for rendering. I'd also like to keep the default field twig

function theme_preprocess_node(&$variables) {
        
   $node = \Drupal::routeMatch()->getParameter('node');
      
    if ($node instanceof \Drupal\node\NodeInterface) {
            
        //Content type
        if($node->bundle() == 'exercices') {
                
            if($node->hasField('field_path')) {
                $path = $node->get('field_path')->getString();
                $extension = substr($path, strrpos($path, '.') + 1);
                $html = '<video controls><source src="' . $path . '" type="video/'.$extension.'">Your browser does not support the video tag</video>';
                    
                //THE FOLOWING LINE WORKS WITH DEFAULT OUTPUT , BUT IF I USE LAYOUT_BUILDER, IT DIDN'T WORK
                $variables['content']['field_path'][0]['#context']['value'] = \Drupal\Core\Render\Markup::create($html);
            }
        }
   }
}

Do you have a better solution ?

4
  • 1
    You say you don't want to do this on field level. The problem is that on node level the last line not only depends on the field layout but also on the field type and formatter. You have to be prepared to adjust the code whenever you reconfigure the content type. BTW in a node preprocess hook don't get the node from the route, get it from $variables['node'].
    – 4uk4
    Commented Dec 11, 2023 at 13:33
  • Please define “better” as it pertains to how we would answer.
    – mona lisa
    Commented Dec 11, 2023 at 14:06
  • 1
    I guess writing a custom text format filter is "better". E.g. lullabot.com/articles/creating-a-custom-filter-in-drupal-8 - was written for Drupal 8 / CKeditor 4, but text filters should still work pretty much the same with Drupal 10 / CKeditor 5
    – Hudri
    Commented Dec 11, 2023 at 14:11
  • Thanks @Hudri, I wrote a custom field text formatter. It works fine Commented Dec 15, 2023 at 15:46

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.