byjg / php-jinja

Jinja for PHP is a PHP implementation of the [Jinja2](http://jinja.pocoo.org/) template engine.
14 stars 3 forks source link

Invalid argument supplied for foreach() #3

Open sevrugin opened 3 months ago

sevrugin commented 3 months ago

Hi Found one issue with my template

#0 _error_handler() called at [/var/www/html/vendor/byjg/jinja-php/src/Template.php:369] 
#1 ByJG\JinjaPhp\Template->ByJG\JinjaPhp\{closure}() 
#2 preg_replace_callback() called at [/var/www/html/vendor/byjg/jinja-php/src/Template.php:351] 
#3 ByJG\JinjaPhp\Template->parseFor() called at [/var/www/html/vendor/byjg/jinja-php/src/Template.php:40] 
#4 ByJG\JinjaPhp\Template->renderTemplate() called at [/var/www/html/vendor/byjg/jinja-php/src/Template.php:32] 
#5 ByJG\JinjaPhp\Template->render()

It happens if I'm using {{ for item in array }}, but I don't have an "array" value in data Is it possible to just ignore not existing variables?

byjg commented 3 months ago

Hello,

The default behavior is throw an error if the variable doesn't exist.

However you can change this by using any of the UndefinedInterface implementation or by creating your own.

The UndefinedInterface is called everytime a variable is undefined.

$template = new Template($templateString);
$template->withUndefined(new DefaultUndefined());  // For each variable doens't exists it will replace by `' ' `  an empty string.