0

I have a situation where I want to change the content of a block on certain conditions, but not permanently.

I'm using a theme_preprocess_block() hook to change the content of the block, but it's not carrying through to the page render:

function MYTHEME_preprocess_block(&$variables) {

  if ( $variables['base_plugin_id'] == 'block_content'
    && $variables['attributes']['id'] == 'block-mycustomfooterblock' ) {

    $variables['content']['#block_content']->set('body', [[
      'value' => 'New Content',
      'format' => 'full_html',
    ]]);

Even after clearing caches, the block content doesn't get replaced with "New Content".

I added this line

$variables['content']['#block_content']->save();

However, that permanently saved the change to the block, which I don't want.

How can I alter the block content just for the page render?

3
  • This seems like a somewhat strange approach. If you have dynamic content, then I'd suggest you define a custom block plugin and output what you need there. Or if you for example have two variations, you could create two blocks and show them based on path or other conditions. I'll guarantee that this is going to confuse someone 6 month later ;)
    – Berdir
    Commented Aug 10, 2018 at 19:47
  • @Berdir I suppose it would-- but how do I get dynamic content on a custom block? Or how can I use "conditions" to decide which of two blocks to display?
    – user1359
    Commented Aug 10, 2018 at 20:32
  • Yes exactly, visibility conditions or a plugin plugin, not a content block, then it is in code from the beginning
    – Berdir
    Commented Aug 10, 2018 at 20:46

2 Answers 2

1

You should probably try

$variables['content']['body'][0]['#text']= "<strong>html content</strong>";

complete example

function THEMENAME_preprocess_block(&$variables) {
  if ( $variables['attributes']['id'] == "block-newblock" ) {
    $variables['content']['body'][0]['#text']= "<strong>html content</strong>";
    $variables['content']['body'][0]['#format']= "full_html";
  }  
}
0

You could write a pre_render function that gets called by hook_block_alter. So in your .module file, you might try this:

use Drupal\Core\Render\Markup;

function MYMODULE_block_view_alter(array &$build, \Drupal\Core\Block\BlockPluginInterface $block) {
    if ($block->getBaseId() === 'mycustomfooterblock') {
        $build['#pre_render'][] = '_MYMODULE_block_customfooter_prerender';
    }
}

function _MYMODULE_block_customfooter_prerender(array $build) {
    $build['content']['#markup'] = Markup::create('New Content');
    return $build;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.