50 lines
1.4 KiB
PHP
50 lines
1.4 KiB
PHP
<?php
|
|
namespace Mince;
|
|
|
|
use Twig\Environment as TwigEnvironment;
|
|
use Twig\Loader\FilesystemLoader as TwigLoaderFilesystem;
|
|
|
|
class Templating {
|
|
private const FILE_EXT = '.twig';
|
|
|
|
private TwigEnvironment $env;
|
|
private TwigLoaderFilesystem $loader;
|
|
private array $vars = [];
|
|
|
|
public function __construct() {
|
|
$this->loader = new TwigLoaderFilesystem;
|
|
$this->env = new TwigEnvironment($this->loader, [
|
|
//'cache' => $cache ?? false,
|
|
'debug' => MCR_DEBUG,
|
|
'strict_variables' => true,
|
|
]);
|
|
}
|
|
|
|
public function addPath(string $path): void {
|
|
$this->loader->addPath($path);
|
|
}
|
|
|
|
public function setVar(string $path, $value): void {
|
|
$path = array_reverse(explode('.', $path));
|
|
$target = &$this->vars;
|
|
$targetName = array_pop($path);
|
|
|
|
if(!empty($path))
|
|
while(($name = array_pop($path)) !== null) {
|
|
if(!array_key_exists($name, $target))
|
|
$target[$name] = [];
|
|
$target = &$target[$name];
|
|
}
|
|
|
|
$target[$targetName] = $value;
|
|
}
|
|
|
|
public function addVars(array $vars): void {
|
|
$this->vars = array_merge($this->vars, $vars);
|
|
}
|
|
|
|
public function render(string $path, array $vars = []): string {
|
|
return $this->env->render($path . self::FILE_EXT, array_merge($this->vars, $vars));
|
|
}
|
|
}
|