Let's say that you've generated some HTML with web2py helpers, and you'd like to display the code in your page using the CODE() helper. The following is an example setup:
div = DIV(SPAN(INPUT(...)), SPAN(INPUT(...)))
code = CODE(str(div).replace('><','>\n<'))
When rendered, the above would show up as a line-numbered version of the following:
<div>
<span>
<input ...>
</span>
<span>
<input ...>
</span>
</div>
Is there a simple way to add indentation formatting to the above, such that it displays in the site as indented HTML code (i.e. does the CODE() helper have any functionality that provides indentation)?
The CODE
helper will not do any formatting of your code, but you can do something like this:
import xml.dom.minidom as xml
def pretty_html(helper, indent=' '):
declaration = len(xml.Document().toxml()) + 1
doc = xml.parseString(helper.xml())
return doc.toprettyxml(indent=indent)[declaration:]
div = DIV(SPAN(INPUT(...)), SPAN(INPUT(...)))
code = CODE(pretty_html(div))