fgh151/yii2-littletwig

This extension allow render twig pages into php layout

v1.0.0 2016-05-25 11:07 UTC

This package is auto-updated.

Last update: 2024-11-13 02:06:54 UTC


README

This extension allow render twig pages into php layout

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist fgh151/yii2-littletwig "*"

or add

"fgh151/yii2-littletwig": "*"

to the require section of your composer.json file.

Usage

First you need add trait to controller:

class TestController extends Controller
{
    use fgh151\littletwig\TwigTrait
    ...
}

now you can render twig page:

public function actionIndex()
{
    return $this->renderTwig('/web/test.twig', ['users' => User::find()->limit(10)->all()], ['Project_Twig_Extension']);
}

Available params: twig page, array of variables array of twig extensions classes (optional)

Twig extensions

To add new extension oyu mast create class, for example:

class Project_Twig_Extension extends \Twig_Extension
{
    public  function  getFunctions()
    {
        return [
            new \Twig_SimpleFunction('TestFunction', function ($p, $p1){ 
                return $p + $p1;
            })
        ];
    }

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

in render function add class:

return $this->renderTwig('/web/test.twig', [], ['Project_Twig_Extension']);

instead callback you may write class function:

class Project_Twig_Extension extends \Twig_Extension
{
    public  function  getFunctions()
    {
        return [
            new \Twig_SimpleFunction('TestFunction', $this->f())
        ];
    }

    public function f($p, $p1)
    {
        return $p + $p1;
    }

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

Now in twig template available function TestFunction :

<p>{{ TestFunction(6, 4) }}</p>

it will render:

<p>10</p>

Twig options

You may path parameters to twig constructor:

$params = [
    'debug' => false,
    'charset' => 'UTF-8',
    'base_template_class' => 'Twig_Template',
    'strict_variables' => false,
    'autoescape' => 'html',
    'cache' => false,
    'auto_reload' => null,
    'optimizations' => -1,
];

return $this->renderTwig('/web/test.twig', [], ['Project_Twig_Extension'], $params);

All params are optional. For params detail see twig documentation