Hi all,
I've a custom-content type defined with the Drupal8 UI.
I'd like to modify the template of the node (node--mycontenttype.html.twig) that shows this content-type adding some sections which list the contents related to this node.
So I have to pass some arrays to the Twig template.

Which is the correct way to do this?
Should I use the preprocess function?

Thank you

claudio

Comments

taggartj’s picture

There are many many many ways to do this evan creating your own form display plugins then you can use in the UI.
this may lead you in the right direction.

/**
 * Implements hook_ENTITY_TYPE_view().
 */
function mymodule_node_view(array &$build, EntityInterface $node, EntityViewDisplayInterface $display) {
  // best to create a service. 
  // return \Drupal::service('mymodule.view_node')->hookNodeView($build, $node, $display);
 $type = $node->getType();
if ($type == 'mycontenttype') {
   $build['stuff'] = [
      '#type' => 'markup',
      '#markup' => '<div>stuff</div>',
    ];
 }
}

this should give you an idea but you can set values etc then call them in your twig template.

ilclaudio’s picture

I don't know if it is the better way, but I've used "hook_preprocess_node" to pass an array to the custom view of the content type: node--mycontenttype.html.twig

function mytheme_preprocess_node(&$variables) {
  $node = \Drupal::routeMatch()->getParameter('node');
  if ($node) {
  	$nid = $node->id();
  	
  	.....getting the data..
  	$deadlines = DeadlinesDBStorage::loadData($nid);
	....
  	$variables['deadlines'] = $deadlines;
	}
}

So in the Twig template I can use the variable {{deadlines}}.

cld