1

I'm using Slim 3 and Slim Twig-View. I want to add a Twig function (or filter, not sure what is the difference?) which generates a random string, and doesn't take any input.

I was able to add a filter like this:

$twig->getEnvironment()->addFilter(
   new \Twig_Filter('guid', function(){ return generateGUID(); })
);

But I can't seem to use it without providing some dummy input:

{{ 0|guid }} This will work
{{ guid }} This will not work

How can I use my guid filter/function without providing any input?

Magnus
  • 17,157
  • 19
  • 104
  • 189

1 Answers1

1

A filter always apply on something, it filters something.

What you want is a function, indeed.
The extending Twig page of the documentation is an incredible source of information on that matter.

At first glance, I would even have said you should define a tag for this but the documentation on the tag, explicitly says:

  • If your tag generates some output, use a function instead.

Source: https://twig.symfony.com/doc/3.x/advanced.html#tags


So indeed, in order to define a function:

Functions are defined in the exact same way as filters, but you need to create an instance of \Twig\TwigFunction:

$twig = new \Twig\Environment($loader); 
$function = new \Twig\Twig_Function('function_name', function () {
    // ... 
}); 
$twig->addFunction($function);

So more specifically for you:

$container->get('view')->getEnvironment()->addFunction(
   new Twig_SimpleFunction('guid', function(){ return generateGUID(); })
);

Will be accessible via:

{{ guid() }}

Other worth reading:

β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83