3

I'm creating a cusom module that loads a node through a view_builder. However, none of the available view_mode display the elements like I'd like them to be, so I'm about to create my own view mode. However, I have parsed quite a few tutorials about view_builders, but none talked about using a custom template (or I missed it)

So, is it possible to use your own template, and how do you do so?

Thank you in advance

3

The standard way to do this is to create a template in your theme, you can use node--nodetype--viewmode.html.twig . (two dashes between each part).

To use it in your custom module, you'd have to use hook_theme_registry_alter to change the path that it looks in for that theme hook.

function mymodule_theme_registry_alter(&$theme_registry) {
  $theme_registry['node__nodetype__viewmode']['path'] = drupal_get_path('module', 'mymodule') . '/templates/';
}

I don't really see the value of moving it into a custom module though. It's a standard to keep custom templates in the theme.

  • This is a specific need, the project I work on is so big that putting in in the theme directory slows everything down. However thank you for your answer, I got to try it and it worked pretty well! – Jaeger Sep 5 '17 at 15:45
0

When calling the view method, the second argument is the name of a view mode:

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21EntityViewBuilderInterface.php/function/EntityViewBuilderInterface%3A%3Aview/8.2.x

Pass in the machine name of the view mode you want to use.

Example:

$view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');
$output = $view_builder->view($node, 'my_view_mode');
  • Yes, that's what I did, but my question is more about if I can use my own template as a view_mode – Jaeger Sep 5 '17 at 15:20
  • 1
    I don't understand what that means, but if you create a new View Mode under Admin > Structure > Display Modes, configure the node display with that view mode, you can certainly then define a node--node_type--view_mode.html.twig template. Thats basically using your 'own' template. From here, you can preprocess and add variables or whatever you want and output them in that twig template. – Kevin Sep 5 '17 at 15:21
  • Oh, okay, do you know if I can put this node--node_type-view_mode.html.twig anywhere? – Jaeger Sep 5 '17 at 15:24
  • I've never tried it from the module level, but you can try and see what happens. – Kevin Sep 5 '17 at 15:25

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.