Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strip whitespace in generated HTML using pure Python code

I am using Jinja2 to generate HTML files which are typically very huge in size. I noticed that the generated HTML had a lot of whitespace. Is there a pure-Python tool that I can use to minimize this HTML? When I say "minimize", I mean remove unnecessary whitespace from the HTML (much like Google does -- look at the source for google.com, for instance)

I don't want to rely on libraries/external-executables such as tidy for this.

For further clarification, there is virtually no JavaScript code. Only HTML content.

like image 614
Sridhar Ratnakumar Avatar asked Jan 26 '10 19:01

Sridhar Ratnakumar


2 Answers

You might also investigate Jinja's built-in whitespace control, which might alleviate some of the need for manually removing whitespace after your templates have been rendered.

Quoting the docs:

But you can also strip whitespace in templates by hand. If you put an minus sign (-) to the start or end of an block (for example a for tag), a comment or variable expression you can remove the whitespaces after or before that block:

{% for item in seq -%}
    {{ item }}
{%- endfor %}

This will yield all elements without whitespace between them. If seq was a list of numbers from 1 to 9 the output would be 123456789.

like image 199
Will McCutchen Avatar answered Oct 12 '22 02:10

Will McCutchen


I found python slimmer library, perfect for what you need to do.

from slimmer import html_slimmer # or xhtml_slimmer, css_slimmer
html = html_slimmer(html)
like image 45
Pykler Avatar answered Oct 12 '22 02:10

Pykler