简体   繁体   中英

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM