Refactoring: moving part of the rendering from html to python.

mark_safe is our friend here.
The big if/else tree is better done in the python code. Otherwise the template and the pyhton
code are tightly coupled.