Sometimes the logic that runs in the template shouldn't be in the template at all ... maybe moving the code into the main_template_vars, perhaps looping through the logic, and producing some variables to echo in the template might be the better choice.