Little Twig
This extension allow render twig pages into php layout, (*1)
Installation
The preferred way to install this extension is through composer., (*2)
Either run, (*3)
php composer.phar require --prefer-dist fgh151/yii2-littletwig "*"
or add, (*4)
"fgh151/yii2-littletwig": "*"
to the require section of your composer.json
file., (*5)
Usage
First you need add trait to controller:, (*6)
class TestController extends Controller
{
use fgh151\littletwig\TwigTrait
...
}
now you can render twig page:, (*7)
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), (*8)
Twig extensions
To add new extension oyu mast create class, for example:, (*9)
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:, (*10)
return $this->renderTwig('/web/test.twig', [], ['Project_Twig_Extension']);
instead callback you may write class function:, (*11)
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 :, (*12)
<p>{{ TestFunction(6, 4) }}</p>
it will render:, (*13)
<p>10</p>
Twig options
You may path parameters to twig constructor:, (*14)
$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, (*15)