'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 1:[1]
Here's what I came up with:
private static function getUserTwigEnvironment(): \Twig\Environment {
return new \Twig\Environment(new NullLoader(), [
'cache' => false,
'debug' => false,
'autoescape' => 'html',
'auto_reload' => false,
'strict_variables' => false,
]);
}
/**
* @param $template_str
* @param $name
* @return \Twig\TemplateWrapper
* @throws \Twig\Error\LoaderError
* @throws \Twig\Error\SyntaxError
*/
public static function createTwigTemplate($template_str, $name=null): \Twig\TemplateWrapper {
return self::getUserTwigEnvironment()
->createTemplate($template_str, $name);
}
public static function renderMyView() {
try {
Util::createTwigTemplate($formData->get('subject'), "Subject Line");
Util::createTwigTemplate($formData->get('header'), "Header Message");
} catch(\Twig_Error_Syntax $error) {
return Util::badRequestError("Invalid syntax: ".$error->getMessage());
}
}
It returns errors like:
Invalid syntax: Unexpected token "name" of value "coach_name" ("end of print statement" expected) in "Header Message (string template ae7778452a2995898cd955d3cecb3a372cfe9b463145417bd172f625b02acd71)" at line 1.
tokenize() will let all kinds of errors slip by.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mpen |
