leforestier / yattag

Python library to generate HTML or XML in a readable, concise and pythonic way.
328 stars 31 forks source link

Add a tag to an existing string? How? #48

Closed bschollnick closed 5 years ago

bschollnick commented 5 years ago

I'm a bit confused on how to do this with yattag...

I have a string, that is going to be passed to a table cell, but it contains \r\n, which I want to convert to a
tag...

row["Ordernote"] = row["Ordernote"].replace("\r\n", "
") - results in
showing in the text field.

But I can't figure out in the yattag frame work, the best way to do this?

Can you point me in the right direction...?

leforestier commented 5 years ago

Good question. Actually, it seems strange that I haven't considered that use case before since it seems pretty common. You could create your custom Doc subclass and override the text method so that it behaves how you like.

Maybe we should have a method for this, though. It would insert the texts after escaping the '<', '>', and '&' characters and replacing the '\n' or '\r\n' sequences with <br> or <br />. What would be good short name for this? Maybe nl2br?

leforestier commented 5 years ago

Actually, I think I'm just going to add a nl2br parameter to the SimpleDoc() constructor. You'll have to call doc, tag, text = Doc(nl2br=True).tagtext() and the text() method would act as you describe in your first post.

leforestier commented 5 years ago

Sorry about the delay, I was busy with other things. You can now use the nl2br option as stated in the previous post.

>>> doc = SimpleDoc(nl2br=True)
>>> doc.text("One\r\nTwo\r\nThree\r\n")
>>> doc.getvalue()
"One<br />Two<br />Three<br />"

If you want simple <br> tags you can use the stag_end option:

>>> doc = SimpleDoc(nl2br=True, stag_end = '>')
>>> doc.text("One\r\nTwo\r\nThree\r\n")
>>> doc.getvalue()
"One<br>Two<br>Three<br>"

By default the stag_end parameter is set to ' />', that's why you get <br /> tags in the first example.

Of course it also works with Unix style newlines (without the '\r'), and the nl2br and stag_end options are also available on the Doc class (which is a subclass of SimpleDoc)

>>> doc = Doc(nl2br=True, stag_end = '>')
>>> doc.text("One\nTwo\nThree\n")
>>> doc.getvalue()
"One<br>Two<br>Three<br>"