[ticket/12891] Replace template loops with 1 loop to reduce generation time

https://tracker.phpbb.com/browse/PHPBB3-12891

Reduced load time with 5k entries from ~20secs to ~7secs