0

I am trying to develop something like this:

In a manged bean, there are String properties that are written in an valid HTML fashion, i.e:

String script = "alert(\"hello!!!!!\");";

String div = "Hello!"

And the purpose for these fields is to dynamically put html components onto the .xhtml file. But if these fields are accessed normally it seems they are only added to the page as text. Is there anyway I can achieve these?

Also, since the actual content of these fields can be quite complicated and the design is to be dynamic, just putting the component in the .xhtml is not an option.

Rui Chen
  • 41
  • 1
  • 10

1 Answers1

7

You can use <h:outputText> together with escape="false". That way the generated stuff will be html code rather than just some text.

e.g., let myBean be the managed bean with the following code,

String div = "<div>Hello World</div>";

In your .xhtml, you would write,

<h:outputText value="#{myBean.div}" escape="false" />

This would result in <div>Hello World</div> being injected as a part of the html code, in other words the <div> tag would be recognized.

Similar thing could be mocked for javaScript code as well, e.g.,

String scriptCode = "<script>function alertHello(){alert('Hello World')}</script>";

In your .xhtml, you would write,

<h:outputText value="#{myBean.scriptCode}" escape="false" />

Sudhansu Choudhary
  • 3,322
  • 3
  • 19
  • 30