I think my solution back in the day was just to include the template files by running a function, something like showTemplate($templateName, $templateVars). The function takes an array as an arg so only these values are available to the template context (apart from the many global vars of course).
You can then run this entire array through htmlentities or htmlspecialchars before doing include().
this is exactly how many modern frameworks do it. your response body is assembled and cached as your application executes, along with any variables it needs, and before the template is rendered the variables are sanitized.
You can then run this entire array through htmlentities or htmlspecialchars before doing include().