What are the best practices for handling context switches in PHP when generating HTML output?

Context switches in PHP can occur when switching between PHP code and HTML output within the same script, leading to decreased performance. To handle context switches efficiently, it is recommended to minimize the number of context switches by separating PHP logic from HTML output. This can be achieved by using PHP to generate data and then using a template engine like Twig to handle the HTML rendering.

<?php
// Generate data in PHP
$data = [
    'name' => 'John Doe',
    'age' => 30
];

// Use Twig template engine to render HTML output
$loader = new \Twig\Loader\FilesystemLoader('path/to/templates');
$twig = new \Twig\Environment($loader);

echo $twig->render('template.html', $data);
?>