Improved variable handling in templates