How does the use of a template engine like Smarty or Twig enhance security in PHP applications compared to native PHP templates?

Using a template engine like Smarty or Twig enhances security in PHP applications compared to native PHP templates by automatically escaping output data, preventing common vulnerabilities like cross-site scripting (XSS) attacks. These template engines also enforce separation of concerns, making it easier to follow best practices for secure coding.

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

$template = $twig->load('index.html');
echo $template->render(['name' => '<script>alert("XSS attack")</script>']);