0

我有一个使用 Slim 版本 2 的旧项目。我无法升级到 3。

我正在尝试将 twig 集成到 slim 2中,同时还保留旧的默认 slim2 渲染器。

目前我有这个。

class TwigView extends \Slim\View
{
    public function rendertwig($template,$data = array()){
        global $twig;

        $twigResults = $twig->render($template,array('test' => '1'));

        $data = array_merge($this->data->all(), $data);
        return $this->render($twigResults, $data);
    }  

}

$view = new TwigView();

$config['view'] = $view; //@JA - This command overides the default render method.

//@JA - Intialize Slim
$app = new \Slim\Slim($config);

$app->view->rendertwig('file.twig')这个想法是,当我需要渲染 twig 模板并$app->render('template.php')用于所有其他使用默认 slim2 模板方法的模板时,我会称之为说。

但是,我收到一个错误,因为在我的 rendertwig 函数中 $this->render() 函数需要第一个参数的模板名称。 有没有一种方法可以直接将 twig 的结果渲染到超薄引擎中,而无需模板文件?

我知道拥有两个模板引擎是不好的形式,但最终我会将所有内容都切换到 Twig,但我需要这个作为临时解决方案,直到我可以修补所有内容。

当我检查 slim 的视图对象时,它将 this 定义为它的渲染方法,这将解释这个问题。

protected function render($template, $data = null)
    {
        $templatePathname = $this->getTemplatePathname($template);
        if (!is_file($templatePathname)) {
            throw new \RuntimeException("View cannot render `$template` because the template does not exist");
        }

        $data = array_merge($this->data->all(), (array) $data);
        extract($data);
        ob_start();
        require $templatePathname;

        return ob_get_clean();
    }
4

1 回答 1

0

我不知道这是否是不好的形式,但我将其作为临时解决方案。

class TwigView extends \Slim\View
{
    public function rendertwig($template,$data = array()){
        global $twig;

        $twigResults = $twig->render($template,array('test' => '1'));
        echo $twigResults;
    }  

}

我看到所有的渲染方法只需要模板,所以我认为只回显来自 twig 模板引擎的结果是安全的吗?这似乎在我的测试中有效。

于 2017-04-15T00:50:09.970 回答