Closing `{% endif %}` should go on a new line (rather a large number of these below).

Make's it easier to see where each conditional ends