in web2py, can I get newlines in the output of HTM

2019-08-11 23:34发布

问题:

I am making a table with web2py HTML helpers. My code is based on the example from the web2py book:

>>> table = [['a', 'b'], ['c', 'd']]
>>> print TABLE(TR(*table[0]), TR(*table[1]))
<table><tr><td>a</td><td>b</td></tr><tr><td>c</td><td>d</td></tr></table>

I have quite a large table, but this approach places all output on one big line. For readability of the HTML, I would appreciate a way to add newlines after each </tr>. I like the HTML helper functions so prefer not to go for the plain {{for ...}} ... {{pass}} approach in the view.

回答1:

A line of python code to insert a '\n' after every row end tag should do the trick. Something like this

{{
table = [['a', 'b'], ['c', 'd']]
table_html=XML(TABLE(TR(*table[0]), TR(*table[1])))
table_html=table_html.replace('</tr>','</tr>\n')
response.write(table_html,escape=False)
}}

What is this doing?

It serializes ( converts to a string ) the TABLE helper, uses the python string attribute replace() to insert the newlines, and finally uses the web2py function response.write() to output the modified string to the document.