简体   繁体   English

树枝渲染文件类型

[英]Twig Render File Type

I need to load both file types (HTML / PHP) as there are multiple files in HTML and PHP. 我需要加载两种文件类型(HTML / PHP),因为HTML和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. 我需要它能够加载HTML和PHP文件,但我似乎无法弄清楚。

Thanks, Jake. 谢谢,杰克。

A raw call to file_exists , as proposed by ceejayoz, will not work if you use templates in namespaced twig paths. 如果在命名空间的树枝路径中使用模板,则ceejayoz提出的对file_exists的原始调用将不起作用。 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 . 也就是说,您可以考虑对template的.twig扩展名进行标准化

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM