Underscore.js Templates Within JSP

前端 未结 5 965
遥遥无期
遥遥无期 2020-12-13 10:08

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 wit

5条回答
  •  猫巷女王i
    2020-12-13 11:00

    @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 ) {
       @>
       
    <@=numPages@>
    <@}@>

    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.

提交回复
热议问题