1

When I create a custom block called Lorem ipsum Dolor, I have not the possibility to choose the machine name. So when I have to make a twig template, the file suggestion is :

block—loremipsumdolor.html.twig

I mean it is without undescore. I found it hard to handle all these twig file when I work on a custom template. It is not human friendly readable.

Is there a way to choose the name of the file name or the block machine name ?

Other example :

Block name : Custom Search form

<!-- FILE NAME SUGGESTIONS:
   * block--customsearchform.html.twig
-->

I have not this problem with node :

node--13--teaser.html.twig

4

Given a block name of 'Custom Search form', you can add to the file name suggestions using a preprocess hook in your theme.

An example of code to add to the .theme file:

/**
 * Add an alternative to file name suggestions the Custom Search form block.
 *
 * Implements hook__suggestions_HOOK_alter().
 * @return array Suggestions.
*/
function mytheme_theme_suggestions_block_alter(array &$suggestions, array $variables) {
    if($variables['elements']['#id'] == 'customsearchform'){
        $suggestions[] = 'block__custom_search_form';
    }
}

This will result in an additional file name suggestion:

<!-- FILE NAME SUGGESTIONS:
   * block--custom-search-form.html.twig * block--customsearchform.html.twig
-->
  • It seems the perfect solution. However, If I had this function to mytheme.theme, I can see in source code the new template file suggestion block--custom-search-form.html.twig. But if I use this template, I don’t see it in front end. If I use the normal file suggestion block--customsearchform.html.twig, I can see my template in front-end. Is there something should do ? – Sébastien Gicquel May 25 '18 at 7:22
  • Apologies - I made a slight error. Correcting the original answer. Twig file suggestions use underscores, which are then converted to dashes for the actual file names. So the suggestion should be block__custom_search_form. – thompsonsj May 25 '18 at 8: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.