jupitern / slim3-skeleton

Slim3 skeleton (http + cli) with some add-ons out of the box
44 stars 12 forks source link

Twig #8

Closed jerfeson closed 6 years ago

jerfeson commented 6 years ago

Can you give me a help, how to set up a twig service provider to replace the plates?

jerfeson commented 6 years ago

I managed to solve it, it's the solution if someone wants to use twig config/app.php

// View settings
        'twig' => [
            'cache' => STORAGE_PATH . 'twig',
            'debug' => true,
            'auto_reload' => true,
        ],

...

// add your service providers here
    // providers bellow are ALWAYS added
    'providers' => [
        ...
        App\ServiceProviders\Twig::class,
    ],

app/ServiceProviders/Twig.php

class Twig implements ProviderInterface
{
    public static function register()
    {
        app()->getContainer()[\Slim\Views\Twig::class] = function ($c) {
            $settings = app()->getConfig('settings');
            $twig = new \Slim\Views\Twig($settings['templates'], $settings['twig']);
            $twig->addExtension(new \Slim\Views\TwigExtension($c->get('router'), $c->get('request')->getUri()));
            $twig->addExtension(new \Twig_Extension_Debug());

            return $twig;
        };
    }

}

app/Http/Controller.php


  /**
     * @param \Psr\Http\Message\ServerRequestInterface $request
     * @param \Psr\Http\Message\ResponseInterface      $response
     * @param Twig                                     $view
     * @param \Psr\Log\LoggerInterface                 $logger
     */
    public function __construct(Request $request, Response $response, Twig $view, LoggerInterface $logger)
    {
        $this->request = $request;
        $this->response = $response;
        $this->view = $view;
        $this->logger = $logger;
    }

app/Http/Site/Welcome.php

    public function index()
    {
        // log some message
        $this->logger->info("log a message");

        return $this->view->render($this->response, "@site/test/welcome.twig", ['test' => "test"]);

    }

resources/views/http/site/test/welcome.twig


    <h1>Welcome</h1>
    <h1>{{ test }}</h1>
jupitern commented 6 years ago

Excelent! thanks. I aded twig to the project.