Underscore.js Templates Within JSP

前端 未结 5 939
遥遥无期
遥遥无期 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条回答
  • 2020-12-13 10:42

    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.

    0 讨论(0)
  • 2020-12-13 10:46

    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
     });`
    
    0 讨论(0)
  • 2020-12-13 10:48

    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.

    0 讨论(0)
  • 2020-12-13 10:54

    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

    0 讨论(0)
  • 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 ) {
       @>
       <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.

    0 讨论(0)
提交回复
热议问题