Skip to content

Commit

Permalink
Add Renderblock extension to twig
Browse files Browse the repository at this point in the history
  • Loading branch information
ChrisRAoW committed Feb 19, 2024
1 parent 5a130cc commit f2ede5a
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
55 changes: 55 additions & 0 deletions src/Extensions/RenderBlockExtension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<?php

namespace OffbeatWP\Twig\Extensions;

use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
use Twig\TwigFunction;
use WP_Embed;

class RenderBlockExtension extends AbstractExtension
{
public function getFunctions()
{
return [
new TwigFunction('render_block', [$this, 'renderBlockFunction'], ['pre_escape' => 'html', 'is_safe' => ['html']]),
];
}

public function getFilters()
{
return [
new TwigFilter('render_block', [$this, 'renderBlockFilter'], ['pre_escape' => 'html', 'is_safe' => ['html']]),
];
}

public function renderBlockFunction($blockName, $attributes = [], $content = null)
{
return $this->renderBlock($blockName, $attributes);
}

public function renderBlockFilter($content, $blockName, $attributes = [])
{
return $this->renderBlock($blockName, $attributes, $content);
}

protected function renderBlock($blockName, $attributes = [], $content = null)
{
$blockArgs = [
'blockName' => $blockName,
'attrs' => $attributes,
'innerBlocks' => []
];

if (!empty($content)) {
$blockArgs['innerHTML'] = (string) $content;
$blockArgs['innerContent'] = [(string) $content];
}

$content = render_block( $blockArgs );

$content = (new WP_Embed)->autoembed($content);

return $content;
}
}
2 changes: 2 additions & 0 deletions src/TwigView.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use OffbeatWP\Contracts\View;
use OffbeatWP\Twig\Extensions\OffbeatWpExtension;
use OffbeatWP\Twig\Extensions\WordpressExtension;
use OffbeatWP\Twig\Extensions\RenderBlockExtension;
use OffbeatWP\Views\Wordpress;
use RuntimeException;
use Twig\Environment;
Expand Down Expand Up @@ -81,6 +82,7 @@ public function getTwig()

$twig->addExtension(new OffbeatWpExtension());
$twig->addExtension(new WordpressExtension());
$twig->addExtension(new RenderBlockExtension());

if (defined('WP_DEBUG') && WP_DEBUG === true) {
$twig->addExtension(new DebugExtension());
Expand Down

0 comments on commit f2ede5a

Please sign in to comment.