I need to load both file types (HTML / PHP) as there are multiple files in HTML and PHP.
/**
* Render the provided view.
*
* @param string $view The view to render.
* @param array $args Array of arguments to pass to the view.
*/
public function render($view, $args = []) {
$this->view = $view;
$this->args = $args;
echo $this->twig->render("{$this->view}.html", $this->args);
}
I need it to be able to load both HTML and PHP files, I just cannot seem to figure this out.
Thanks, Jake.
A raw call to file_exists
, as proposed by ceejayoz, will not work if you use templates in namespaced twig paths. Then this will do better, as it resolves the paths through the file loader first:
$view = '';
$loader = $this->twig->getLoader();
if($loader->exists('{$this->view}.html')) {
$view = '{$this->view}.html';
} else if($loader->exists('{$this->view}.php')) {
$view = '{$this->view}.php';
} else {
throw new \RuntimeException('View not found');
}
echo $this->twig->render($view, $args);
Something like this should work:
if(file_exists("{$this->view}.html")) {
echo $this->twig->render("{$this->view}.html", $this->args);
} elseif(file_exists("{$this->view}.php")) {
echo $this->twig->render("{$this->view}.php", $this->args);
} else {
throw new Exception('uh oh');
}
That said, you might consider standardizing on the .twig
extension for templates .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.