Answer the question
In order to leave comments, you need to log in
How to add user functions to Twig?
Decided to try Twig for a new project. I can't figure out how to add my own functions.
For example, you need to insert articles selected by id from the table into the template.
Function example:
function get_article($id) {
//делаем выборку из БД и записываем в result
return $result;
}
Answer the question
In order to leave comments, you need to log in
twig.sensiolabs.org/doc/advanced.html
<?php defined('SYSPATH') or die('No direct script access.');
class My_Twig_Extension extends Twig_Extension {
public function getName()
{
return 'my_twig';
}
public function getFilters()
{
return array();
}
public function getFunctions()
{
return array(
'get_article' => new Twig_Function_Method($this, 'get_article',
array('is_safe' => array('html'))),
);
}
function get_article($id) {
//делаем выборку из БД и записываем в result
return $result;
}
public function getTests()
{
return array();
}
}
<?php defined('SYSPATH') or die('No direct script access.');
return array(
'default' => array(
'extensions' => array(
'My_Twig_Extension',
),
),
);
Create a class based on the class Twig_Extension
, describe your function in it and add it to the overridden method getFunctions()
(the name of the function that will be called in twig), then when creating the twig object, add an instance of your class to
$Twig->addExtension(new MyTwigExtension());
it You can read it here: twig.sensiolabs.org/doc/ advanced.html
I use this option for myself:
// Регистрация функции
$twig->addFunction('pluginIsActive', new Twig_Function_Function('getPluginStatusActive'));
// Сама функция
function getPluginStatusActive($pluginID){
...
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question