Skip to content

Instantly share code, notes, and snippets.

@henrytran9x
Created December 21, 2016 09:56
Show Gist options
  • Save henrytran9x/f6cc1b14b5ed9700c9929fcee58b237d to your computer and use it in GitHub Desktop.
Save henrytran9x/f6cc1b14b5ed9700c9929fcee58b237d to your computer and use it in GitHub Desktop.
Module Create function Twig Block render
name: Mod Block Twig
type: module
description: Create function twig render display block
package: Custom module - Required
dependencies:
- block
core: 8.x
version: 1.0
<?php
use Drupal\block\Entity\Block;
use Drupal\block\BlockInterface;
use Drupal\file\Entity\File;
use Drupal\context\ContextInterface;
function _render_block($id){
$block = \Drupal\block\Entity\Block::load($id);
$block_content = \Drupal::entityManager()
->getViewBuilder('block')
->view($block);
return array('#markup' => drupal_render($block_content));
}
services:
mod_block_twig.twig.render_block:
class: Drupal\mod_block_twig\Twig\BlockExtension
tags:
- { name: twig.extension }
<?php
/**
* @file
* Contains \Drupal\mod_block\Twig\BlockExtension.
*/
namespace Drupal\mod_block_twig\Twig;
use Drupal\block\BlockInterface;
use Drupal\Core\Entity\EntityInterface;
class BlockExtension extends \Twig_Extension{
/**
* Returns the name of the extension.
*
* @return string The extension name
*/
public function getName()
{
return 'render_block';
}
/**
* {@inheritdoc}
*/
public function getFunctions()
{
return array(
new \Twig_SimpleFunction('render_block', array($this, 'render_block'), array(
'is_safe' => array('html'),
)),
);
}
public function render_block($id)
{
$block = \Drupal\block\Entity\Block::load($id);
if(isset($block) && !$this->check_block_visibility($block)){
unset($block);
return ;
}
else if(isset($block) && $block->getTheme()) {
$block_content = \Drupal::entityTypeManager()->getViewBuilder('block')->view($block);
return \Drupal::service('renderer')->render($block_content);
}
}
public function check_block_visibility($block)
{
$visibility = $block->getVisibility();
if(isset($visibility) && isset($visibility['request_path'])) {
$negate = $visibility['request_path']['negate'];
$path = str_replace('/','',strtolower(\Drupal::service('path.current')->getPath()));
$pages = $visibility['request_path']['pages'];
$page_match = \Drupal::service('path.matcher')->matchPath($path,$pages);
if($negate == false && $page_match){
return true;
}
elseif($negate == true && $page_match){
return false;
}
}
else{
return true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment