Refactor template engine as library

This pull request fixes Trac ticket #17093.
Is this code just copied from a previous function, and you're trying to change it as little as possible?

If not, seems to me it ought to be restructured to wrap only the loader call in the `try` block.