This whole construction is rather ugly. Doesn't twig provide things so the logic can be deduplicated?