Reworked template handling to be more efficient and to support inner templates.