views:

110

answers:

4

Hello,

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!

A: 

Maybe use a <pre> tag.

dhill
I've finally used format_to_html in the python code.
infinito
A: 
  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.

bart
A: 

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
infinito
Forget to say this runs on Trac.
infinito
+1  A: 

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))}
voyager