Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Underscore.js Templates Within JSP

Underscore.js templates use <%= %> for variable interpolation. Unfortunately that is also interpreted in a JSP (or GSP). Is there a way to use Underscore.js templates within JSPs?

like image 380
erturne Avatar asked Apr 24 '11 16:04

erturne


2 Answers

Add the following interpolate and evaluate settings in your jsp page

_.templateSettings = {     interpolate: /\<\@\=(.+?)\@\>/gim,     evaluate: /\<\@(.+?)\@\>/gim,     escape: /\<\@\-(.+?)\@\>/gim }; 

then you can write your qualify underscore variables,if and for statements with <@ @> instead of <% %> and will not conflict with jsp

like image 53
coderman Avatar answered Sep 22 '22 04:09

coderman


@coderman's example was helpful, but, unfortunately, it doesn't work if you want to use newlines in your templates. For example:

   <@        var numPages = 10;       if ( numPages > 1 ) {    @>    <div><@=numPages@></div>    <@}@> 

The problem is that the regex for evaluate won't match across newlines as described here: JavaScript regex multiline flag doesn't work

So, the solution that worked for me is:

_.templateSettings = {     interpolate: /\<\@\=(.+?)\@\>/gim,     evaluate: /\<\@([\s\S]+?)\@\>/gim,     escape: /\<\@\-(.+?)\@\>/gim }; 

NOTE: [\s\S] in the evaluate regexp. That's the key.

like image 29
Upgradingdave Avatar answered Sep 22 '22 04:09

Upgradingdave