Inline (?) HTML formatting inside a TemplateRenderer

Viewed 121

I'm just looking for a technique for using basic HTML formatting inside Vaadin 14 Grid TemplateRenderers.

I use many ComponentRenderers that I want to change to TemplateRenderers to improve performance.

My problem is I have a lot of "free form" HTML formatting in the text that is easy to do in ComponentRenderer such as ...

new Span(new Html("<p>Some <b> formatted </b>text</p>"));

What is a normal syntax or technique to put that in via TemplateRenderer withProperty(...)?

I think just need it to do the same job as new Html(...)

Any information much appreciated.

2 Answers

There is a dirty trick for making a TemplateRenderer use the data it receives as HTML, and that is to assign it as the innerHTML property of a wrapper element. This in turn requires another dirty trick with the way Polymer converts between CamelCase and dash-case for converting between case insensitive attribute names and case sensitive property names.

Before showing the example, I also feel bound to warn you against using showing user-provided data as HTML since that's an excellent way of causing cross-site scripting vulnerabilities in your application.

With that out of the way, a simple working example goes like this:

grid.addColumn(TemplateRenderer.<MyItem> of("<div inner-h-t-m-l='{{item.html}}'><div>")
  .withProperty("html", item -> "<i>Hello</i>"));

TemplateRenderer accepts any HTML, just like new Html(). The only difference is that you can bind properties you pass in through withProperty(). In your case, you don't seem to need any properties.

To use your example above, you can do:

grid.addColumn(TemplateRenderer.of("<span><p>Some <b> formatted </b>text</p></span>"));

Read more about the TemplateRenderer on the docs page https://vaadin.com/docs/v14/flow/components/tutorial-flow-grid#using-template-renderers

PS. Placing a <p> inside a <span> tag goes against the HTML spec (block element inside an inline element).

Related