More robust toCode util function and more accurate id name for sub-templates