web-base/core/Elements/TemplateDocument.class.php

78 lines
2.3 KiB
PHP
Raw Normal View History

2021-12-08 16:53:43 +01:00
<?php
namespace Elements;
use Objects\User;
use Twig\Environment;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
use Twig\Error\SyntaxError;
use Twig\Loader\FilesystemLoader;
class TemplateDocument extends Document {
private string $templateName;
protected array $parameters;
private Environment $twigEnvironment;
private FilesystemLoader $twigLoader;
2022-02-20 16:53:26 +01:00
protected string $title;
2021-12-08 16:53:43 +01:00
public function __construct(User $user, string $templateName, array $initialParameters = []) {
parent::__construct($user);
2022-02-20 16:53:26 +01:00
$this->title = "";
2021-12-08 16:53:43 +01:00
$this->templateName = $templateName;
$this->parameters = $initialParameters;
$this->twigLoader = new FilesystemLoader(WEBROOT . '/core/Templates');
$this->twigEnvironment = new Environment($this->twigLoader, [
'cache' => WEBROOT . '/core/TemplateCache',
'auto_reload' => true
]);
}
protected function getTemplateName(): string {
return $this->templateName;
}
protected function loadParameters() {
}
public function getCode(): string {
parent::getCode();
$this->loadParameters();
return $this->renderTemplate($this->templateName, $this->parameters);
}
public function renderTemplate(string $name, array $params = []): string {
try {
$params["user"] = [
"lang" => $this->user->getLanguage()->getShortCode(),
"loggedIn" => $this->user->isLoggedIn(),
2022-02-20 16:53:26 +01:00
"session" => (!$this->user->isLoggedIn() ? null : [
"csrfToken" => $this->user->getSession()->getCsrfToken()
])
2021-12-08 16:53:43 +01:00
];
$settings = $this->user->getConfiguration()->getSettings();
$params["site"] = [
"name" => $settings->getSiteName(),
"baseUrl" => $settings->getBaseUrl(),
2022-02-21 14:04:49 +01:00
"registrationEnabled" => $settings->isRegistrationAllowed(),
2022-02-20 16:53:26 +01:00
"title" => $this->title,
2021-12-08 16:53:43 +01:00
"recaptcha" => [
"key" => $settings->isRecaptchaEnabled() ? $settings->getRecaptchaSiteKey() : null,
"enabled" => $settings->isRecaptchaEnabled(),
],
"csp" => [
"nonce" => $this->getCSPNonce(),
"enabled" => $this->isCSPEnabled()
]
];
return $this->twigEnvironment->render($name, $params);
} catch (LoaderError | RuntimeError | SyntaxError $e) {
return "<b>Error rendering twig template: " . htmlspecialchars($e->getMessage()) . "</b>";
}
}
}