Refactor compileTemplate method