nKognito
nKognito

Reputation: 6363

Using ampersand sign within client-side template and render it with thymeleaf

I use jsrender lib for client-side template generation but the whole website's output is processed by thymeleaf (spring mvc). The problem is that js template contains condtiion i.e.

<script id="main-menu-form-tmpl" type="text/x-jsrender">
        {{if (index && (index == 0 || ... 

but thymeleaf requires all the ampersands be escaped as &amp;, but this causes jsrender to fail. Another solution found here, but jsrender fails as well because of unknown syntax.

Is there any way to output script's content without parsing it with thymeleaf engine?

Upvotes: 1

Views: 522

Answers (1)

BorisMoore
BorisMoore

Reputation: 8524

JsRender lets you register templates from strings, as well as from script blocks.

See http://www.jsviews.com/#compiletmpl.

So instead of writing:

var mainTemplate = $.templates("#main-menu-form-tmpl");

and then calling mainTemplate.render(...) or mainTemplate.link(...) etc. you can instead remove your template script block and instead pass your template markup as a string to $.templates() as in:

var mainTemplate = $.templates("... {{if (index && (index == 0 || ...");
...

Or if you want you can keep the script block declaration, but with escaped ampersands and then get the contents of the script block as a string, unescape the ampersands, and pass that string to your template definition:

var mainTemplateString = $("#main-menu-form-tmpl").text().replace(/&amp;/g, "&");
var mainTemplate = $.templates(mainTemplateString);
...

Alternatively you can wrap your template block in <![CDATA and again, strip the wrapper to get the real template markup string you want to pass to the template definition:

var mainTemplateString = $("#main-menu-form-tmpl").text().slice(16, -10);
var mainTemplate = $.templates(mainTemplateString);
...

Upvotes: 2

Related Questions