How do popular PHP template engines like Twig handle the evaluation of code snippets in templates compared to using eval()?

Popular PHP template engines like Twig handle the evaluation of code snippets in templates by using a sandboxed environment that restricts the execution of potentially harmful code. This approach ensures better security and prevents the execution of arbitrary PHP code. In contrast, using the eval() function in PHP can pose security risks as it allows the execution of any PHP code within the template.

// Example of using Twig template engine to render a template
$loader = new \Twig\Loader\FilesystemLoader('/path/to/templates');
$twig = new \Twig\Environment($loader, [
    'cache' => '/path/to/cache',
    'auto_reload' => true,
]);

$template = $twig->load('template.twig');
echo $template->render(['name' => 'John']);