开发者

Creating readable html with django templates

When using Django for html templating how do I create good html markup formatting.

I am trying to make use of content blocks. But the content blocks show up at different levels of indentation in different templates. How do I get the content blocks to show indented like it would be if someone was to hand write the html.

I am having the same problem with newlines; I can smash all the blocks together in the template. At that point the html looks better, but the templates are unmaintainable.

I guess the question is how to you create pretty html markup with the django 开发者_如何学Gotemplating system?

I am surprised by the answers so far. I find that nicely formatted HTML aids in writing the corresponding CSS and JavaScript. As well as making it easier to add content later on.


Christian S. Perone from Pyevolve has exactly what you're looking for. He uses middleware to intercept the HTTPResponse object and run it through BeautifulSoup.

I'd imagine that your site will suffer a slight performance hit, though. I recommend running some benchmarks before deploying this middleware to a production site.


You can override the NodeList's render method as I've done. See my question with working code:

Proper indentation in Django templates (without monkey-patching)?


I'm impressed you care about the resulting html - I only worry about getting the templates tidy and readable! But in answer to your question, have you looked at middleware?

http://docs.djangoproject.com/en/dev/topics/http/middleware/

Then use the Tidy python module to reformat the html.

http://pypi.python.org/pypi/PythonTidy/


I recommend to run the output of the template engine through an HTML tidier, such as µTidylib.


The readability of HTML doesn't matter. In a system like Django or Rails, HTML is an output format, not a source format. When people edit HTML by hand, they are right to be concerned about indentation and spacing, because it is a source format, and someone will have to edit it in the future. But the output of templates is just that: output. The browser doesn't care about the indentation. At this point the only people who read the HTML are people looking at View - Source.


If you're using Django Templates to do string-formatting of long-but-simple strings, you can use Python's triple-quoted strings with .format() in a function def:

def templated_string(context_dict):
    return '''This is an example
of a long string across multiple lines.
It can be used to format {something} for 
{name}'s own purposes, even though
it looks funny in code'''.format(**context_dict)

Then templated_string({'name': 'rileymat', 'something': 'whatever you want'}) does the sensible thing. You can generate raw HTML that way... which then has exactly the whitespace you ask for.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜