Slim 2 Render Direct HTML

716 views Asked by At

I have an old project I'm working on using Slim version 2. I can not upgrade to 3.

I'm trying to integrate twig into slim 2 while also keeping the old default slim2 renderer.

Currently I have this.

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);

The idea is that I would call this saying $app->view->rendertwig('file.twig') when I need to render the twig templates and use $app->render('template.php') for all the other templates that use the default slim2 method of templating.

However, I get an error because in my rendertwig function $this->render() function requires a template name for the first parameter. Is there a way I can render directly the results from twig into the slim engine without needing a template file?

I'm aware this is bad form to have two templating engines but eventually I will switch everything to Twig but I need this as a temporary solution till I can patch everything over.

When I inspected slim's view object it has this defined as its render method which will explain the issue.

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();
    }
1

There are 1 answers

0
Joseph Astrahan On BEST ANSWER

I don't know if this is bad form but I did this as a temporary solution.

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

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

}

I saw that all the render method did was just require the template so I figured its safe to just echo the results from the twig templating engine? This seemed to work from my test.