简单,在Symfony2应用程序中,在服务类的函数内部,我想检查作为参数传递的给定字符串是否具有有效的Twig语法...
public function checkIfValidTwig($twigString)
{
$isValid = false;
$isValid = someWay->toCheckIf()->itIsValid($twigString);
return $isValid;
}
有什么想法吗?
答案 0 :(得分:3)
您可以使用Twig_Environment::tokenize()
,如果无法解析Twig代码,则会引发异常Twig_Error_Syntax
- 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;
}
}
}
答案 1 :(得分:2)
你需要创建Constraint类,幸运的是,你在这里有你问题的上下文中描述的确切过程:
http://labs.octivi.com/validation-constraint-for-twig-template-syntax/