I am building a Drupal 8 site. The site will have basic pages (nodes) that have three fields: a title, a body and a list of embedded blocks. The idea is to allow the editors to create content blocks by using the new functionality of Block Types in Drupal 8. Those blocks can be referenced and arrangaed inside the page by using an entity reference field.
I have built the necessary infrastructure and I can reference my custom blocks from the page and render them in the template. The trouble comes when I want to set a custom template for my blocks, for example I would like to have a custom template: block--image-gallery-block.html.twig that would be used when rendering blocks of type Image Gallery Block.
With Twig debug mode enabled I can see that Drupal is looking for a template for the entity reference field, and then starts to render the referenced block fields instead of the block itself, so I can not use any template for it (not even the default block.html.twig).
I've thought about using a custom template for my field and render here the block the way I like. Unfortunately my field can reference blocks of multiple types, so this solution won't work for me.
How can I make Drupal pick the proper template for the referenced blocks?
I am explaining here the solution I've ended with after reading @ssibal and @4k4 answers.
- I've built some new content-types that will represent the blocks.
- I've modified my Basic Page content type to have an entity reference field that points to the blocks. This field simply references other nodes from the content types that I want (the ones I've made in the step 1).
- In the display options of my basic page, I choose which view mode I want to use for rendering the blocks.
- I use the view mode that I've set up in the step 3 to build custom templates for my block content types.
- Since I do not want block content types to be accessed directly with a URL, I've implemented a hook_node_access to throw a 404 error when directly loading a node of my block content types.