[英]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... 很简单,在Symfony2应用程序的服务类函数内部,我想检查作为参数传递的给定字符串是否具有有效的Twig语法...
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 您可以使用Twig_Environment::tokenize()
,如果无法解析Twig代码,则会抛出异常Twig_Error_Syntax
- http: Twig_Error_Syntax
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: 您需要创建Constraint类,所幸的是,这里有针对您的问题描述的确切过程:
http://labs.octivi.com/validation-constraint-for-twig-template-syntax/ http://labs.octivi.com/validation-constraint-for-twig-template-syntax/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.