0

I wish to register a template file for use with a filed item, but I can't wrap my head around it.

here is what I am trying to achieve. In my field widget Formatter

public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];

foreach ($items as $delta => $item) {
  $elements[$delta] = [
    '#markup' => $this->viewValue($item),
    '#theme' => 'my-field-item-template',
  ];
}

return $elements;

}

Then in my .module file

function mymodule_theme($existing, $type, $theme, $path){
return array('myplugin' =>
    array(
        'variables' => array(
            'other elements' => 'other elements',
            ), 
            'template' => 'my-field-item-template'
        )
    );

}

I wish to print my 'variables' in my twig file, I believe my template file is not registered for use with my field item this way. What's the right way?

0

In hook_theme you define and register your templates.

In your code your template will be "myplugin". To use that template you need to specify "#theme" => "myplugin" in your render array (not my-field-item-template). Then twig tries to render your content with the file called "myplugin.html.twig". This twig file should be stored in the templates directory of your module.

You may read this https://www.drupal.org/docs/8/theming/twig/debugging-twig-templates to learn more about debugging theming.

  • grateful again..I got my template file registered – Nicholas Dec 14 '18 at 8:35

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.