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?

2 Answers 2

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());
2
  • 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. Commented Oct 7, 2016 at 21:22
  • Thanks Mats Mikkel Rummelhoff (again). Those caveats were a response to one of my previous questions :) Commented Oct 8, 2016 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);
  }));
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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