samer.j92
samer.j92

Reputation: 85

Modifying SQLFORM text output - line breaks, paragraphs (web2py framework)

Model:

Field('text1', type='text', length=1000, notnull=True)

Function:

def textinput():
f=SQLFORM(db.example, fields=['text1'])
if f.accepts(request.vars, session):
return dict(form=f)

I want to be able to display the 'text1' field with proper line spacing/formatting. If a user was to press the [enter] key in the form to start a new line or whole new paragraph, I want this to reflect on the view.

For example, if a user enters the following into a SQLFORM:

This is a paragraph. Blah blah blah blah blah blah blah.
Blah blah blah blah blah blah blah blah blah.
Blah blah blah blah.

This is another paragraph. Blah blah blah blah blah.
Blah blah blah blah blah.

I want it to come out exactly like that in the view, instead of having it all crammed up with no spacing. How would I go about doing this? I was thinking about using the .replace method and replacing all [enter] keystrokes with a line break, but I'm not sure how to do it. I've searched all over Google but I can't find my exact issue.

Any help would be greatly appreciated. Thanks.

Upvotes: 3

Views: 2496

Answers (1)

Anthony
Anthony

Reputation: 25536

The easiest method is to wrap the text in a <pre> tag and use CSS to control the styling. You can also replace the line breaks ('\n') with <br /> tags. If you are displaying the text via a readonly SQLFORM, a Crud read form, a SQLTABLE, or SQLFORM.grid, then you can set the field's "represent" attribute to control the display:

Using <pre>:

Field('text1', type='text', length=1000, notnull=True,
    represent=lambda text, row: PRE(text))

Using line break replacement:

Field('text1', type='text', length=1000, notnull=True,
    represent=lambda text, row: XML(text.replace('\n', '<br />'),
        sanitize=True, permitted_tags=['br/']))

If you're inserting the text manually into a view, you can simply use either of the above methods directly in the view. For example:

{{=PRE(row.text1)}}

Note, browsers typically display text in a <pre> tag with a fixed-width font. If you don't want that, you'll need to use CSS to change the font.

Upvotes: 5

Related Questions