28

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?

erturne
  • 1,799
  • 1
  • 15
  • 29

5 Answers5

74

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

bcoughlan
  • 25,987
  • 18
  • 90
  • 141
coderman
  • 1,485
  • 1
  • 16
  • 15
  • 27
    yes it was answered, but this is for those coders (like me) who would rather have a copy-paste solution :) – coderman Dec 15 '11 at 08:03
  • I have added that block in and changed all of my tags to <@ @> and it doesnt seem to be working. Can anyone shed some light on what Im doing wrong? – jrutter Jul 24 '12 at 21:42
  • 1
    @coderman Thank you for understanding the true needs of the average programmer in a hurry – Jay Mar 29 '13 at 00:53
25

@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.

Cheeso
  • 189,189
  • 101
  • 473
  • 713
Upgradingdave
  • 12,916
  • 10
  • 62
  • 72
16

According to the webpage you linked to:

If ERB-style delimiters aren't your cup of tea, you can change Underscore's template settings >to use different symbols to set off interpolated code.

It suggests you change the interpolate and evaluate regexes. This means you can change the <%= %> usage to something that doesn't conflict with JSP.

Zameer Manji
  • 3,017
  • 5
  • 31
  • 42
  • 1
    Oh jeez, I guess that I had better RTFM! Now don't I feel stupid. ;-) Thanks for the quick response... problem solved. – erturne Apr 24 '11 at 17:06
5

The problem can be solved by escaping <% sequence in code:

<script id="tmpl" type="text/x-template">
    <span>Hello, <\%=name%></span>
</script>

So you don't need to change any template engine logics.

Andrey Atapin
  • 7,745
  • 3
  • 28
  • 34
0

Another option that doesn't require global replace is to specify the interpolate and evaluate to specific method invocation

 _.template($("#template-id").html(),null, {
   interpolate :  /\{\{\=(.+?)\}\}/g,
   evaluate: /\{\{(.+?)\}\}/g
 });`
katzmopolitan
  • 1,371
  • 13
  • 23