You've already forked wp-bootstrap
73 lines
1.9 KiB
PHP
73 lines
1.9 KiB
PHP
|
|
<?php
|
||
|
|
/**
|
||
|
|
* Twig Template Engine Service.
|
||
|
|
*
|
||
|
|
* @package WPBootstrap
|
||
|
|
* @since 0.0.1
|
||
|
|
*/
|
||
|
|
|
||
|
|
namespace WPBootstrap\Twig;
|
||
|
|
|
||
|
|
use Twig\Environment;
|
||
|
|
use Twig\Loader\FilesystemLoader;
|
||
|
|
use Twig\TwigFunction;
|
||
|
|
|
||
|
|
class TwigService
|
||
|
|
{
|
||
|
|
private static ?TwigService $instance = null;
|
||
|
|
private Environment $twig;
|
||
|
|
|
||
|
|
private function __construct()
|
||
|
|
{
|
||
|
|
$viewsDir = get_template_directory() . '/views';
|
||
|
|
$cacheDir = WP_CONTENT_DIR . '/cache/twig';
|
||
|
|
|
||
|
|
$loader = new FilesystemLoader($viewsDir);
|
||
|
|
$this->twig = new Environment($loader, [
|
||
|
|
'cache' => WP_DEBUG ? false : $cacheDir,
|
||
|
|
'debug' => WP_DEBUG,
|
||
|
|
'auto_reload' => true,
|
||
|
|
]);
|
||
|
|
|
||
|
|
$this->registerWordPressFunctions();
|
||
|
|
}
|
||
|
|
|
||
|
|
public static function getInstance(): self
|
||
|
|
{
|
||
|
|
if (self::$instance === null) {
|
||
|
|
self::$instance = new self();
|
||
|
|
}
|
||
|
|
return self::$instance;
|
||
|
|
}
|
||
|
|
|
||
|
|
public function render(string $template, array $context = []): string
|
||
|
|
{
|
||
|
|
return $this->twig->render($template, $context);
|
||
|
|
}
|
||
|
|
|
||
|
|
public function display(string $template, array $context = []): void
|
||
|
|
{
|
||
|
|
$this->twig->display($template, $context);
|
||
|
|
}
|
||
|
|
|
||
|
|
public function getEnvironment(): Environment
|
||
|
|
{
|
||
|
|
return $this->twig;
|
||
|
|
}
|
||
|
|
|
||
|
|
private function registerWordPressFunctions(): void
|
||
|
|
{
|
||
|
|
$this->twig->addFunction(new TwigFunction('__', function (string $text, string $domain = 'wp-bootstrap'): string {
|
||
|
|
return __($text, $domain);
|
||
|
|
}));
|
||
|
|
|
||
|
|
$this->twig->addFunction(new TwigFunction('_e', function (string $text, string $domain = 'wp-bootstrap'): void {
|
||
|
|
_e($text, $domain);
|
||
|
|
}));
|
||
|
|
|
||
|
|
$this->twig->addFunction(new TwigFunction('esc_html', 'esc_html'));
|
||
|
|
$this->twig->addFunction(new TwigFunction('esc_attr', 'esc_attr'));
|
||
|
|
$this->twig->addFunction(new TwigFunction('esc_url', 'esc_url'));
|
||
|
|
}
|
||
|
|
}
|