Fix bug with template rendering, and optimize more