hanyuu/src/Templating/TemplateContext.php

57 lines
1.8 KiB
PHP

<?php
namespace Hanyuu\Templating;
use Closure;
class TemplateContext {
private const EXT = '.php';
private string $pathFormat = '%s' . self::EXT;
private TemplateVars $vars;
private array $blocks = [];
private array $functions = [];
public function __construct($path = '') {
if(!empty($path))
$this->pathFormat = rtrim($path, '\\/') . DIRECTORY_SEPARATOR . '%s' . self::EXT;
$this->vars = new TemplateVars;
$this->defineFunction('global', $this->vars->getVar(...));
$this->defineFunction('getBlock', $this->getBlock(...));
$this->defineFunction('x', fn(string $string) => htmlspecialchars($string, ENT_QUOTES, 'utf-8', true));
}
public function setGlobal(string $name, mixed $value): void {
$this->vars->setVar($name, $value);
}
public function removeGlobal(string $name): void {
$this->vars->removeVar($name);
}
public function defineFunction(string $name, Closure|callable $function): void {
$this->functions[$name] = $function;
}
public function getFunctions(): array {
return $this->functions;
}
public function create(string $path): Template {
return new Template($this, new TemplateVars($this->vars), sprintf($this->pathFormat, $path));
}
public function exists(string $path): bool {
return is_file(sprintf($this->pathFormat, $path));
}
public function render(string $path, array $vars = [], ?TemplateSelf $self = null): string {
return $this->create($path)->render($vars, $self);
}
public function getBlock(string $name, mixed $default = ''): string {
return ($this->blocks[$name] ?? new TemplateBlock(new \stdClass, $default))->render();
}
public function setBlock(string $name, TemplateBlock $block): void {
$this->blocks[$name] = $block;
}
}