diff --git a/CHANGES.rst b/CHANGES.rst index ad9aaf0308..4d605ac9eb 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -17,6 +17,7 @@ Changelog **Changed** +- #1451 Render Analysis Remarks in Listings as HTML - #1445 Allow formatted HTML in the other rejection reasons - #1428 Publish verified partitions - #1429 Add2: Do not set template values on already filled fields diff --git a/bika/lims/api/__init__.py b/bika/lims/api/__init__.py index 17741e1069..aa4d63a2d9 100644 --- a/bika/lims/api/__init__.py +++ b/bika/lims/api/__init__.py @@ -1376,3 +1376,23 @@ def to_display_list(pairs, sort_by="key", allow_empty=True): dl = dl.sortedByValue() return dl + + +def text_to_html(text, wrap="p", encoding="utf8"): + """Convert `\n` sequences in the text to HTML `\n` + + :param text: Plain text to convert + :param wrap: Toggle to wrap the text in a + :returns: HTML converted and encoded text + """ + if not text: + return "" + # handle text internally as unicode + text = safe_unicode(text) + # replace newline characters with HTML entities + html = text.replace("\n", "
") + if wrap: + html = u"<{tag}>{html}".format( + tag=wrap, html=html) + # return encoded html + return html.encode(encoding) diff --git a/bika/lims/browser/analyses/view.py b/bika/lims/browser/analyses/view.py index dee675bea0..197322c201 100644 --- a/bika/lims/browser/analyses/view.py +++ b/bika/lims/browser/analyses/view.py @@ -1216,6 +1216,10 @@ def _folder_item_remarks(self, analysis_brain, item): if self.is_analysis_edition_allowed(analysis_brain): item["allow_edit"].extend(["Remarks"]) + else: + # render HTMLified text in readonly mode + item["Remarks"] = api.text_to_html( + analysis_brain.getRemarks, wrap=None) def _append_html_element(self, item, element, html, glue=" ", after=True): diff --git a/bika/lims/tests/doctests/API.rst b/bika/lims/tests/doctests/API.rst index a969cdf2f3..e6f4b28a8d 100644 --- a/bika/lims/tests/doctests/API.rst +++ b/bika/lims/tests/doctests/API.rst @@ -1601,3 +1601,40 @@ It can be sorted either by key or by value: >>> api.to_display_list(pairs, sort_by="value") + + +Converting a text to HTML +------------------------- + +This function converts newline (`\n`) escape sequences in plain text to `
` +tags for HTML rendering. + +The function can handle plain texts: + + >>> text = "First\r\nSecond\r\nThird" + >>> api.text_to_html(text) + '

First\r
Second\r
Third

' + +Unicodes texts work as well: + + >>> text = u"Ä\r\nÖ\r\nÜ" + >>> api.text_to_html(text) + '

\xc3\x83\xc2\x84\r
\xc3\x83\xc2\x96\r
\xc3\x83\xc2\x9c

' + +The outer `

` wrap can be also omitted: + + >>> text = "One\r\nTwo" + >>> api.text_to_html(text, wrap=None) + 'One\r
Two' + +Or changed to another tag: + + >>> text = "One\r\nTwo" + >>> api.text_to_html(text, wrap="div") + '

One\r
Two
' + +Empty strings are returned unchanged: + + >>> text = "" + >>> api.text_to_html(text, wrap="div") + ''