Mixing any logic beyond that with HTML makes a mess of both.
I'm personally a fan of minimalist templating engines that provide only simple loops and conditionals so that template has to receive prepared data tree which is created by the actual programming language first and passed into the template.