0
votes

I have created a custom block though Drupal Admin mentioning page restrictions (to show only on listed pages) and have included this block programmatically in a node twig file but, this block shows up in all the node pages rather than only mentioned pages. How to restrict this block to display only on restricted pages through coding?

I have already restricted the pages in block (created through Admin interface) but the block is being displayed irrespective of it's page restriction on all node pages.

// Code in .theme file, which works irrespective of pages mentioned in configuration settings for "show only on listed pages":

function my_sitedesigntheme_theme_preprocess_node(&$variables) {
    $block = Drupal\block_content\Entity\BlockContent::load(31);
    $variables['my_block_data'] = \Drupal::entityTypeManager()->getViewBuilder('block_content')->view($block);
}

// Code in twig file:

{{ my_block_data }}

The block should be displayed (which is already being displayed) but only on listed pages in custom block config settings.

1
Why wouldn't you just place your block in a region via the block UI, that way it would work as expected. The was you are doing it circumvents the visibility checking for the block (which I am guessing is done in somewhere where the region content is determined)2pha
Because I have to insert it between page title and body of the node. Hence, I have to edit node twig for my particular content type. Is there any other way to resolve this problem?Larry Thomson
In that case I would usually make a new region in your theme, render the region in the main page template where you need, then place your block in the UI2pha

1 Answers

0
votes

When you build a block with \Drupal::entityTypeManager()->getViewBuilder('block_content')->view($block) it ignores configurations(eg, pages which you want block to shown). So, this way is not correct.

the solution for you is, use the theme block manager, and put the block in the region you want.