Refactor template engine as library

This pull request fixes Trac ticket #17093.