infinito
infinito

Reputation: 2075

Print string as HTML

I would like to know if is there any way to convert a plain unicode string to HTML in Genshi, so, for example, it renders newlines as <br/>.

I want this to render some text entered in a textarea.

Thanks in advance!

Upvotes: 1

Views: 870

Answers (4)

Esteban K&#252;ber
Esteban K&#252;ber

Reputation: 36852

If Genshi works just as KID (which it should), then all you have to do is

${XML("&lt;p&gt;Hi!&lt;/p&gt;")}

We have a small function to transform from a wiki format to HTML

def wikiFormat(text):
    patternBold = re.compile("(''')(.+?)(''')")
    patternItalic = re.compile("('')(.+?)('')")
    patternBoldItalic = re.compile("(''''')(.+?)(''''')")
    translatedText = (text or "").replace("\n", "<br/>")
    translatedText = patternBoldItalic.sub(r'<b><i>\2</i></b>', textoTraducido or '')
    translatedText = patternBold.sub(r'<b>\2</b>', translatedText or '')
    translatedText = patternItalic.sub(r'<i>\2</i>', translatedText or '')
    return translatedText

You should adapt it to your needs.

${XML(wikiFormat(text))}

Upvotes: 1

infinito
infinito

Reputation: 2075

In case anyone is interested, this is how I solved it. This is the python code before the data is sent to the genshi template.

from trac.wiki.formatter import format_to_html
from trac.mimeview.api import Context
...
    context = Context.from_request(req, 'resource')
    data['comment'] = format_to_html(self.env, context, comment, True)
    return template, data, None

Upvotes: 0

bart
bart

Reputation: 7777

  1. Convert plain text to HTML, by escaping "<" and "&" characters (and maybe some more, but these two are the absolute minimum) as HTML entities

  2. Substitute every newline with the text "<br />", possibly still combined with a newline.

In that order.

All in all that shouldn't be more than a few lines of Python code. (I don't do Python but any Python programmer should be able to do that, easily.)

edit I found code on the web for the first step. For step 2, see string.replace at the bottom of this page.

Upvotes: 0

dhill
dhill

Reputation: 3447

Maybe use a <pre> tag.

Upvotes: 0

Related Questions