Vaadin 11: Problem rendering GridColumn as dynamic HTML content using Templ

Hi,

I’m using Vaadin 11.0.1 and want to specify a custom column for my Grid component rendering dynamic HTML content. The problem is that I don’t know exactly how the data to render will look like, so I have created a method, which preprocesses the content, adding some additional HTML-tags if necessary before TemplateRenderer gets the data. But the problem is that TemplateRenderer.withProperty(x) will always treat the injected values as value-String, displaying the HTML-tags in the text. Since I don’t know how many modifications I have to apply to the String I can’t use the Template of the TemplateRenderer itself to solve the problem.

private void initGrid() {
	grid.addColumn(TemplateRenderer.
		<MyClass>of("<ul style=\"list-style-type:none;\">[[item.value]
]</ul>")
		.withProperty("value", o -> getModifiedValue(o.getItemString())));
}

Is there a way to tell TemplateRenderer to treat the injected content as plain HTML? Or is there a better solution in Vaadin 11 to render HTML Grid-Cells? (I can’t find something equivalent to HTMLRenderer from previous releases other than TemplateRenderer)

I would appreciate if you can help!

Cheers,
Peter

Hi Peter,

There’s a way to make a TemplateRenderer to render the HTML as the content of the element. It’s a bit ugly though:

grid.addColumn(TemplateRenderer
                .<MyClass> of("<ul inner-h-t-m-l=\"[[item.html]
]\"></ul>")
                .withProperty("html", o -> getModifiedValue(o.getItemString())));

Basically with this you are setting the innerHTML property of the <ul> element with the value from your lambda, without any escaping. Beware that this is extremely unsafe to use, if the HTML you’re setting is not fully managed by your application.


Gilberto

Hi Gilberto,

Thank you very much for your reply on my question. Good to know that there is a way to do it as well.

In the meantime I tried a different approach utilizing a ComponentRenderer instead of the TemplateRenderer and I’m quite happy that this is - at least for me - a very comfortable way to generate dynamic table cells with the feeling that it’s done in a manageable manner.

Thanks, Peter

Yes, ComponentRenderer is the most versatile way to put whatever you want in the cells, but it comes with a cost: when used in large Grids, ComponentRenderers have a bigger impact on performance than TemplateRenderers.

But of course is totally fine if you don’t have too many cells rendered at the same time.

Glad it worked for you!


Gilberto