Properly count newlines appearing at the end of templates after rendering

Fixes #4633