Sometimes templating isn't an option, or isn't enough. You have to make sure you escape in the right context.
I've seen developers use PHP's htmlspecialchars() (or hand-rolled versions thereof) when rendering snippets of inline JavaScript. The problem is that only HTML entity encodes <, >, &, ', and ", which still leaves you open to XSS because it doesn't encode all the characters that can be exploited in a JavaScript context.
Following the OWASP guidelines will negate all of that danger.