twigslim

Create custom extension


I have created a template manager with Slim+Twig and it works well. The problem is when trying to add an Extension, I get an error when calling the extension from the .twig file, and I don't know exactly what the error could be:

index.php

<?php

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;
use Slim\Views\Twig;
use Slim\Views\TwigMiddleware;

use Helpers\PaginatorTwigExtension;

require __DIR__ . '/vendor/autoload.php';

// Create App
$app = AppFactory::create();

// Create Twig
$twig = Twig::create('path/to/templates', ['cache' => false]);

// Add Twig-View Middleware
$app->add(TwigMiddleware::create($app, $twig));

$app->addErrorMiddleware(true, true, true);

$app->get('/', function ($request, $response) use () {
    $view = Twig::fromRequest($request);

    return $view->render($response, 'index.twig', []);
});

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

PaginatorTwigExtension.php

<?php

namespace Helpers;

use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

/**
 * Twig extension to help generate simple paginations.
 */
class PaginatorTwigExtension extends AbstractExtension
{

    public function getName()
    {
        return 'paginator';
    }

    public function getFunctions()
    {
        return [
            new TwigFunction('paginator', [$this, 'generatePaginationData']),
        ];
    }

    public function generatePaginationData(int $curr_page, int $last_page, int $num_items = 7, string $separator = '...')
    {
        return array(
            'curr_page' => $curr_page,
            'last_page' => $last_page,
            'num_items' => $num_items,
            'separator' => $separator,
            'pagination' => $pagination
        );
    }
}

When calling the extension from the index.twig file, I do it like this:

{% set paginator = paginator(10, 25 , 11, '...') %}

But it gives me this error:

Unknown "paginator" function.

My question is, am I missing something to include this custom extension? Or should we call it something else?


Solution

  • You need to register the extension via the addExtension() method:

    $twig->addExtension(new \Helpers\PaginatorTwigExtension());