phptemplatestwig

How to syntax check / lint a Twig template programmatically


My application users can enter some Twig template strings. I'd like to validate the syntax of the given template. How to accomplish that?

I've been thinking possibility to just simply try to render the template and catch possible errors, but I can't provide all possible variables that user may have entered in the template.


Solution

  • Use Twig_Environment::tokenize(). if the twig code cannot be parsed, it will throw an Twig_Error_Syntaxexpection. So you can catch the error.