hanyuu/src/Templating/Template.php

51 lines
1.8 KiB
PHP

<?php
namespace Hanyuu\Templating;
use RuntimeException;
class Template {
public function __construct(
private TemplateContext $context,
private TemplateVars $vars,
private string $path
) {}
public function setVar(string $name, mixed $value): void {
$this->vars->setVar($name, $value);
}
public function removeVar(string $name): void {
$this->vars->removeVar($name);
}
public function render(array $vars = [], ?TemplateSelf $self = null): string {
if(!is_file($this->path))
throw new RuntimeException('Template file does not exist: ' . $this->path);
$self = new TemplateSelf($this->context->getFunctions() + $vars + $this->vars->getVars(), $self);
$self->tplPath = $this->path;
$self->var = fn(string $name, mixed $default = null) => $this->vars->getVar($name, $default);
$self->setVar = fn(string $name, mixed $value) => $this->vars->setVar($name, $value);
$self->remVar = fn(string $name) => $this->vars->removeVar($name);
$self->block = fn(string $name, mixed $contents) => $this->context->setBlock($name, new TemplateBlock($self, $contents));
$self->include = fn(string $name) => $this->context->render($name, [], $self);
$self->ctx = $this->context;
$self->extends = fn(string $name) => $self->extends = $name;
ob_start();
(static function() use ($self) { include $self->tplPath; })();
$buffer = ob_get_contents();
ob_end_clean();
if(is_string($self->extends)) {
if(!empty($buffer))
throw new RuntimeException('You cannot output from templates that extend another.');
$buffer = $this->context->render($self->extends, [], $self);
}
return $buffer;
}
}