3

I have a custom entity 'sponsor'.

I want to create a custom template for that entity. But I still want to use the formatter settings that have been defined in the UI.

So

  • I set the viewbuilder to the default EntityViewBuilder in my annotation
  • I defined the theme hook 'sponsor' in my .module file

    function sponsors_theme(){
    $theme_hook= array(
        'sponsor'=>array(
            'variables'=>array(
                'sponsor'=>null,
    
    
            ),
    
            'template'=>'sponsor',
        )
    );
    
    return $theme_hook;
    

    }

  • Then I created my sponsor.html.twig file

Now I can access the raw values through {{sponsor.field.value}}

But I don't want to access all fields through their raw values. I still want to use the formatters.

Is there anyone who can tell me how to do that or point me to the right docs?

Matt.

5

You could craft a variable that holds all entity fields with respect to their order and formatter settings.

/**
 * Implements hook_theme().
 */
function sponsor_theme() {
  return [
    'sponsor' => [
      'render element' => 'elements',
    ],
  ];
}

/**
 * Prepares variables for sponsor templates.
 */
function template_preprocess_sponsor(&$variables) {
  // Helpful $content variable for templates.
  $variables['content'] = [];
  foreach (Element::children($variables['elements']) as $key) {
    $variables['content'][$key] = $variables['elements'][$key];
  }
}

This approach is used by core entities (node, user, comment etc).

| improve this answer | |
  • 3
    Correct, but that's just one, what's important for this is to define your theme entry with render element => elements. See also drupal.org/node/2808481, that will provide a default entity template with suggestions and everything that's needed, so zero custom code is required to display a content entity with fields. – Berdir Nov 25 '16 at 19:56
  • 1
    Thanks a lot guys! I had been searching for this for a long time. Good thing this will be kind of automated through the default entity template. Good idea! – DragonEye Nov 26 '16 at 12:33

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.