Fix bugs in template replacement