Django template formatting leads to "ragged" html
To my convenience I use some formatting in my templates (line breaks, spacing, etc.) For example:
{% extends "base.html" %}
{% load tabs %}
{% block content %}
{% block navigation %}
<ul id="user_admin_tabs_list">
<li><a href="{% url user_admin.views.profile %}" class=
{% ifactivetab "user_admin_开发者_JAVA技巧tabs" "profile" %}
"user_admin_tabs_active_tab"
{% else %}
"user_admin_tabs_inactive_tab"
{% endifactivetab %}>Профиль</a></li>
...
But this leads to "ragged" html output. Like this:
<ul id="user_admin_tabs_list">
<li><a href="/accounts/profile/profile/" class=
"user_admin_tabs_active_tab"
>Профиль</a></li>
<li><a href="/accounts/profile/shops/" class=
"user_admin_tabs_inactive_tab"
>Магазины</a></li>
<li><a href="/accounts/profile/billing/" class=
"user_admin_tabs_inactive_tab"
>Биллинг</a></li>
<li><a href="/accounts/profile/settings/" class=
"user_admin_tabs_inactive_tab"
>Настройки</a></li>
</ul>
Therefore readability of templates causes bad readability of output html.
What is the decision of this problem?
To be honest, I wouldn't worry about the output of the template engine. You're going to be editing the templates, not the output, so for maintainability, it only really matters if the template HTML is well-structured. Sure, if someone uses "View Source" on your webpage, they'll see a mess of HTML, but that doesn't really matter that much.
That said, you could try using Django's spaceless
tag to get prettier HTML output.
Edit
For this specific case, you could put the ifactivetab
tags inline:
<li><a href="{% url user_admin.views.profile %}" class="{% if activetab "user_admin_tabs" "profile" %}user_admin_tabs_active_tab{% else %}user_admin_tabs_inactive_tab{% endifactivetab %}">Профиль</a></li>
I've thought about this in the past.
Your best bet IMO is to post process the output with something like tidy
. It's written in C so it's pretty fast and won't incur much of a performance hit. It's an option in development but not something you want in production on a high traffic site.
You'll want to configure it to only indent code.
Off hand, I think it might try to clean up invalid markup which'll leave you scratching your head when you enable/disable it. Something to be aware of because the structure of your document might change as a result.
It's kind of nice if you're "viewing source" but you're probably better off just using firebug to examine your output anyway - if that's the motivation.
精彩评论