Skip to content

Instantly share code, notes, and snippets.

@wlkns
Created February 19, 2019 12:58
Show Gist options
  • Select an option

  • Save wlkns/cc57cb7d73ccaec3b02947249f0ea1cb to your computer and use it in GitHub Desktop.

Select an option

Save wlkns/cc57cb7d73ccaec3b02947249f0ea1cb to your computer and use it in GitHub Desktop.
Laravel Validate Twig Template
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use Twig_Environment;
use Twig_Filter;
use Twig_Loader_Array;
use Twig_Error_Syntax;
class ValidTwigTemplate implements Rule
{
private $_twig_error;
/**
* Create a new rule instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $template)
{
try {
$loader = new Twig_Loader_Array(['template' => $template]);
$twig = new Twig_Environment($loader);
$twig->render('template', []);
}
catch(Twig_Error_Syntax $e)
{
$this->_twig_error = $e->getMessage();
return false;
}
catch(Exception $e)
{
return false;
}
return true;
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return $this->_twig_error ?: 'The template has an error.';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment