In what scenarios would it be more beneficial to use a template engine like Twig instead of manually filtering variables in PHP code?

When working with complex HTML templates that require dynamic data insertion, using a template engine like Twig can simplify the process of separating logic from presentation. Twig provides a more readable and maintainable way to render templates by allowing developers to focus on the structure of the template rather than worrying about filtering and escaping variables manually in PHP code.

// Using Twig to render a template with dynamic data
require_once 'vendor/autoload.php';

$loader = new Twig_Loader_Filesystem('templates');
$twig = new Twig_Environment($loader);

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