Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Twig with a Slim application

Tags:

php

twig

slim

I'm using the Slim framework for a simple website I'm developing and would also like to use the Twig templating engine.

I've installed Slim, Slim Extras and Twig and my index.php file has the following content:

<?php

/* Require and initialize Slim and Twig */
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
require 'Twig/lib/Twig/Autoloader.php';
Twig_Autoloader::register();

$app = new \Slim\Slim(array(
    'view' => new \Slim\Extras\Views\Twig()
));

/* Application routes */
$app->get('/', function () {
    $pageTitle = 'hello world';
    $body = 'sup world';

    $app->view()->setData(array('title' => $title, 'body' => $body));
    $app->render('index.html');
});

/* Run the application */
$app->run();

However, this results in an error: Fatal error: Call to a member function view() on a non-object in C:\xampp\htdocs\index.php on line 18

I'll admit I have no idea how to properly use Twig with Slim. I followed a StackOverflow post on the directory structure and how to load Twig, but I don't know how to add some custom data to a view and I don't know where the view files for Twig should be stored.

I googled but a lot of the information is for older versions of Slim and the Slim documentation itself is lacking.

Thanks!

like image 547
James Dawson Avatar asked Dec 03 '22 00:12

James Dawson


1 Answers

This is a simple php error. You're trying to access a variable in a closure that's not imported into its scope, fix it like this:

$app->get('/', function () use ($app) {
    // $app will work here
});
like image 120
Maerlyn Avatar answered Dec 20 '22 21:12

Maerlyn