html helper: CODE (scroll or word-wrap)

35 views
Skip to first unread message

lucas

unread,
Sep 19, 2021, 7:32:39 AM9/19/21
to web2py-users
hello one and all,

using the CODE() html helper, how can we get either a scrollbar enabled when the code window doesn't fit in its container, OR, word-wrap enabled to soft linefeed long lines of code?  i see that it outputs a table of the scripted code but are there setting to facilitate the latter two possibilities?

thank you in advance, lucas

Anthony

unread,
Oct 4, 2021, 9:46:11 AM10/4/21
to web2py-users
As noted in the CODE documentation, you can pass in a styles dictionary to override the default styles controlling the display of the code. To see the keys of that dictionary that can be used to override various styles, see the source code at https://github.com/web2py/web2py/blob/master/gluon/highlight.py#L192 and https://github.com/web2py/web2py/blob/master/gluon/highlight.py#L284.

In particular, the default styles for the "CODE" key (which get applied to each pre element) are:

'''
font-size: 11px;
font-family: Bitstream Vera Sans Mono,monospace;
background-color: transparent;
margin: 0;
padding: 5px;
border: none;
overflow: auto;
white-space: pre !important;
'''


Notice that white-space is set to pre, which only wraps at newlines and <br> elements. You can override that by supplying a custom set of "CODE" styles:

code_styles = '''
font-size: 11px;
font-family: Bitstream Vera Sans Mono,monospace;
background-color: transparent;
margin: 0;
padding: 5px;
border: none;
overflow: auto;
white-space: pre-wrap;
'''


code = CODE(my_code, styles=dict(CODE=code))

The above sets white-space to pre-wrap, which will allow wrapping (though note that it will not preserve indentation on the wrapped lines, so may not look great).

To add scrollbars, you can simply set the overflow CSS property on the container element:

div = DIV(CODE(my_code), _style="width:50%; overflow: scroll")

Given the above, if the table created by CODE exceeds the width of the containing div, a horizontal scrollbar will be added. Of course, the above can also be achieved via CSS rules in a stylesheet.

Anthony

Reply all
Reply to author
Forward
0 new messages