3

I was on the Twig StackExchange forum and found an answer that suited my needs.

But I can't for the life of me figure out how to implement this into a Craft CMS Plugin.

I'm familiar with Twig_Function_Method and Twig_Filter_Method, but I can't find anything on Twig_SimpleTest.

Has the option to include "tests" been omitted from Craft CMS?

3

When you call Craft's TemplatesService->getTwig() (craft()->templates->getTwig()), you get an instance of the Twig environment and from there you could be able to call addTest.

100% untested, but something like this should work:

$twig = craft()->templates->getTwig();
$twig->addTest(new My_Twig_SimpleTest());
| improve this answer | |
  • 2
    Note that if you want to get back the same Twig environment instance that Craft is actually using to render templates, there are some caveats, outlined here. – Mats Mikkel Rummelhoff Oct 7 '16 at 21:22
  • Thanks Mats Mikkel Rummelhoff (again). Those caveats were a response to one of my previous questions :) – Mark Notton Oct 8 '16 at 14:42
3

Thanks Brad, that's what I was after. In the case of what I was trying to achieve; the following in my plugins init function did the job:

$twig = craft()->templates->getTwig();

$twig->addTest(new \Twig_SimpleTest('array', function ($value) {
  return is_array($value);
}));

I always struggle with syntax, so hopefully this example will help others.


Craft 3 Solution:

Add this to your plugins main init() function:

$this->addTests(Craft::$app->view->getTwig());

Then add this function after the init():

private function addTests($twig) {
  // Is String
  $twig->addTest(new \Twig_SimpleTest('string', function ($value) {
    return is_string($value);
  }));
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.