Extract file writing logic from Template.