Refactor template engine as library

This pull request fixes Trac ticket #17093.
Yes, this is copied code - ignore my comment.