views:

109

answers:

1

I have a servlet coded in Scala. I have some code like this in there:

def message = <HTML><HEAD><TITLE>Test</TITLE></HEAD><BODY>{value}</BODY></HTML>
def value = "Hello <BR/> World"

The corresponding HTML code generated for value is

Hello &lt;BR/&gt; World

How do I get it to generate the HTML code (shown below)?

Hello <BR/> World

Thanks in advance

+7  A: 

If you don’t mind changing the type of value to xml.Elem, you can do

def value = <xml:group>Hello <BR/> World</xml:group>

Addition

In my opinion, you should type as much XML inline as possible. Only then will you have compile time validation of the input. All other solutions either give you a runtime exception at some point (say, you forgot some /) or might even break your XML layout.

However, if you really want to have an easy transform, you could do this:

class XmlString(str: String) {
  def assumeXML = xml.XML.loadString("<xml:group>" + str + "</xml:group>")
  def toUnparsedXML = new xml.Unparsed(str)
}
implicit def stringToXmlString(str: String) = new XmlString(str)

def value = "Hello <BR/> World"

and then (for some reason, it still shows the <xml:group> part; you could get rid of it with xml.NodeSeq.fromSeq(value.assumeXML.child) or similar)

def message = <HTML><HEAD><TITLE>Test</TITLE></HEAD><BODY>{value.assumeXML}</BODY></HTML>

or even (well, you would not need the implicit here, Unparsed(value) would do)

def message = <HTML><HEAD><TITLE>Test</TITLE></HEAD><BODY>{value.toUnparsedXML}</BODY></HTML>

The assumeXML method will fail with at runtime, if you provide invalid XML; toUnparsedXML will accept all input, even data that is potentially dangerous.

Debilski
Thanks for the answer! I was hoping there was an easier way. However, in the end, keeping it as `xml.Elem` makes more sense, though it involved a bit of code-changing.
Jus12