M
M
Mikhail Tverdokhleb2012-11-12 13:18:08
PHP
Mikhail Tverdokhleb, 2012-11-12 13:18:08

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;
}


How to connect such a function to the project and how to access the result of the function from the template itself?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
N
NeX, 2012-11-12
@NeX

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();
  }
}

In twig config:
<?php defined('SYSPATH') or die('No direct script access.');

return array(
  'default'    => array(
    'extensions' => array(
      'My_Twig_Extension',
    ),
  ),
);

E
enchikiben, 2012-11-12
@EnChikiben

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

V
Vitaly, 2012-11-23
@vp7

I use this option for myself:

// Регистрация функции
$twig->addFunction('pluginIsActive',	new Twig_Function_Function('getPluginStatusActive'));

// Сама функция
function getPluginStatusActive($pluginID){
...
}

S
Sergey, 2012-11-12
Protko @Fesor

In general, such things are usually done through HMVC.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question