简体   繁体   中英

Check if string has valid Twig syntax

Simple, in a Symfony2 app, inside a function of a service class, I want to check if a given string passed as argument has valid Twig syntax...

public function checkIfValidTwig($twigString)
{
    $isValid = false;
    $isValid = someWay->toCheckIf()->itIsValid($twigString);
    return $isValid;
}

Any idea?

You can use Twig_Environment::tokenize() , which will throw an exception Twig_Error_Syntax if the Twig code cannot be parsed - http://twig.sensiolabs.org/doc/internals.html#the-lexer

class TwigValidator
{
    /**
     * @var \Twig_Environment
     */
    private $twig;

    /**
     * @param \Twig_Environment $twig
     */
    public function __construct(\Twig_Environment $twig)
    {
        $this->twig = $twig;
    }

    /**
     * @param string $twigString
     *
     * @return boolean
     */
    public function checkIfValidTwig($twigString)
    {
        try {
            $this->twig->tokenize($twigString);

            return true;
        } catch (\Twig_Error_Syntax $e) {

            return false;
        }
    }
}

You need to create Constraint class, fortunately, you have here the exact procedure described in the context of your problem:

http://labs.octivi.com/validation-constraint-for-twig-template-syntax/

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