2

I'm trying to make custom block but I have problem accessing variables in template.

My block code:

namespace Drupal\more_topics_rollout\Plugin\Block;
use Drupal\Core\Block\BlockBase;
/**
 *
 * @Block(
 *  id = "more_topics_rollout",
 *  admin_label = @Translation("More topics rollout"),
 *  category = @Translation("Blocks")
 * )
 */
class more_topics_rollout_block extends BlockBase {
    /**
     * {@inheritdoc}
     */
    public function build() {
        return array(
            '#title' => 'More topics'
        );
    }
}
?>

My module file:

function more_topics_rollout_theme($existing, $type, $theme, $path) {
    return array('more_topics_rollout' =>
        array(
            'variables' => array(
                'title' => null,
                'body' => null,
                'description' => null
            ),
            'template' => 'block--more-topics-rollout'
        )
    );
}

And when I'm trying to display title with {{ title }} it doesn't render. When I'm trying to access variables I know for sure don't exist like {{ dasdasda }} it doesn't throw any errors. Can someone explain this behavior to me?

5

Can someone explain this behavior to me?

The render array returned by the build method in the block plugin does not have a theme or type. This means that it will default to markup (iirc). The theme/template is not being used because the render array does not specify to use it.

You can find an example of implementing render arrays on drupal.org's documentation page, Render arrays. This explains the default element properties.

How to pass variable from block and access in it twig template?

The render array should have the #theme element property set to the theme definition key.

  public function build() {
    return [
      '#theme' => 'more_topics_rollout',
      '#title' => $this->t('More Topics'),
      '#body' => 'My body',
      '#description' => 'My description'
    ];
  }
0

I figured out why I wasn't able to access my variables from twig. In order to to this your custom block class needs to implement BlockPluginInterface. Maybe it will help someone else.

0

We ended up solving this issue by adding a param during the preprocess hook - in our case we were modifying the easy_social module to include the current page url

/**
 * Implements hook_preprocess_HOOK() for easy_social theme.
 *
 * @see easy_social_theme()
 * @see theme_easy_social()
 */
function easy_social_preprocess_easy_social(&$variables) {

  // ...

  $variables['path'] =  Url::fromRoute('<current>',array(),array('absolute'=>'true'));

  // ...
}

And then in our Twig file:

<p>Your current page is {{ path }}</p>

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.