kisphp/twig-extensions

Kisphp twig extensions

1.4.0 2022-12-14 19:17 UTC

This package is auto-updated.

Last update: 2024-11-05 09:24:35 UTC


README

pipeline status coverage report

Installation

composer require kisphp/twig-extensions

Usage

Create twig Filter

<?php

namespace AppBundle\Twig\Filters;

use Kisphp\Twig\AbstractTwigFilter;

class DemoFilter extends AbstractTwigFilter
{
    /**
     * @return string
     */
    protected function getExtensionName()
    {
        return 'demo';
    }

    /**
     * @return \Closure
     */
    protected function getExtensionCallback()
    {
        return function ($name) {
            // add here your filter logic
        };
    }
}


<?php

namespace AppBundle\Twig\Functions;

use Kisphp\Twig\AbstractTwigFunction;

class DemoFunction extends AbstractTwigFunction
{
    /**
     * @return string
     */
    protected function getExtensionName()
    {
        return 'demo';
    }

    /**
     * @return \Closure
     */
    protected function getExtensionCallback()
    {
        return function ($name) {
            // add here your function logic
        };
    }
}

Register new twig extensions

<?php

namespace AppBundle\Twig;

use AppBundle\Twig\Functions\DemoFunction;
use AppBundle\Twig\Filters\DemoFilter;
use Twig\Extension\AbstractExtension;

class TwigExtension extends AbstractExtension
{
    public function getFunctions()
    {
        return [
            DemoFunction::create(),
        ];
    }

    public function getFilters()
    {
        return [
            DemoFilter::create(),
        ];
    }
}

If your function of filter has dependencies then you can instantiate them like this:

public function getFunctions()
{
    $myCustomDependency = 'object, variable, array or what ever you need here';

    return [
        (new DemoFunction($myCustomDependency))->getExtension(),
    ];
}