Drupal 代码方式显示/隐藏block

注: 此文适用于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']);
  }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容