Yuck, it is ugly to be doing this much python woven into a template like this.  I see you're just following the pattern here, but it's ugly.  Better if it was factored into the view code that renders this template.  

I don't recommend fixing this as part of this PR, just complaining.