Saturday, November 11, 2006

Edit HTML code in a HTML form

If you want to edit HTML code online, say in a html text input field or a textarea, then HTML escaped characters make some problems:

1) type "€" in a text field or textarea

2) submit the form
3) reload it: you will see the escaped character "€" but not "€" as your previous input was
4) submit again: the "€" character will be stored but not the HTML escape code

Here is a small function that prepares the pure HTML code for the right display code in the text fields or textarea fields:


def getHtmlForTextInput(text):
"""
Returns a HTML code that displays the HTML escaped chars well in 
HTML form fields like text fields or textareass.
"""
myRE = re.compile('&\w*;')

result = ''
pos = 0
while True:
m = myRE.search(text, pos)
if m is None:
break
result += text[pos:m.start()]
result += m.group().replace('&', '&')
pos = m.end(0)

result += text[pos:]

return result

No comments: