Drupal 代码方式显示/隐藏block

2023-12-27  本文已影响0人  又起风了_

注: 此文适用于Drupal8及以上版本

  1. 显示block到特定twig中
    如果覆写的是page模板,需要在YourTheme_preprocess_page或YourTheme_preprocess_pageName中把block加载进去,这里演示的是一个block嵌入另一个block中
 // your_theme.theme

/**
 * HOOK THEME_preprocess_block
 *
 * @param $variables
 */
function YourTheme_preprocess_block__xx_xx_pagetitle(&$variables) {
  $breadcrumbs = \Drupal\block\Entity\Block::load('my_breadcrumbs_block_id');
  $variables['my_breadcrumbs'] = \Drupal::entityTypeManager()
    ->getViewBuilder('block')
    ->view($breadcrumbs);
}
<!-- block--xx-xx-pagetitle.html.twig -->
<div class="page-title-and-breadcrumbs">
    <div{{ attributes }}>
        {{ title_prefix }}
        {% if label %}
            <h2{{ title_attributes }}>{{ label }}</h2>
        {% endif %}
        {{ title_suffix }}
        {% block content %}
            {{ content }}
        {% endblock %}
    </div>
    {{ my_breadcrumbs }}
</div>
  1. 隐藏block
function YourTheme_preprocess_html(&$var) {
  //dump($var);
  //可以根据页面,或者根据用户权限来控制block是否显示
  if (!$var['is_admin']) {
    unset($var['page']['header']['my_breadcrumbs']);
  }
}
上一篇 下一篇

猜你喜欢

热点阅读