PHP code example of onethity / slim4-twig-view

1. Go to this page and download the library: Download onethity/slim4-twig-view library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

onethity / slim4-twig-view example snippets


// Create Container
$container = new Container();

// Set container to create App with on AppFactory
AppFactory::setContainer($container);
$app = AppFactory::create();

// Register Twig View helper
$container->set('view', function ( ) use ($app) {
    $view = new \Slim\Views\Twig(__DIR__ . '/../tpl/', [
        'cache' => false,
    ]);
    
    // Instantiate and add Slim specific extension
    $uriFactory = new \Slim\Psr7\Factory\UriFactory();
    $uri = $uriFactory->createFromGlobals($_SERVER);
    $routeParser = $app->getRouteCollector()->getRouteParser();
    $basePath = $app->getBasePath();
    $view->addExtension(new \Slim\Views\TwigExtension($routeParser, $uri, $basePath));

    return $view;
});

// Define named route
$app->get('/hello/{name}', function ($request, $response, $args) {
    return $this->get('view')->render($response, 'index.html.twig', [
        'name' => $args['name']
    ]);
})->setName('profile');

// Render from string
$app->get('/hi/{name}', function ($request, $response, $args) {
    $str = $this->get('view')->fetchFromString('<p>Hi, my name is {{ name }}.</p>', [
        'name' => $args['name']
    ]);
    $response->getBody()->write($str);
    return $response;
});

// Run app
$app->run();