Velocity Templates - New Line

后端 未结 6 1185
醉话见心
醉话见心 2021-02-13 04:07

I\'ve been working with Apache\'s Velocity engine and a custom template.
The thing is, that I haven\'t been able to generate a String with the corresponding line breaks. I t

相关标签:
6条回答
  • 2021-02-13 04:44

    It might be easiest to simply use the Velocity EscapeTool.

    See this link: https://velocity.apache.org/tools/releases/2.0/javadoc/org/apache/velocity/tools/generic/EscapeTool.html#getNewline%28%29

    Example Usage: Line Break Here: $esc.newline This is on a new line.

    0 讨论(0)
  • 2021-02-13 04:46

    I needed a new line for generating javascript. Well, I didn't need it of course, but it made reading the generated code easier while developing. In this case, I just set a variable so that the Velocity was easier to read. This is all you need:

    Velocity Code:

    #set( $newline="
    ")
    #set( $jsCode = "var bling='blang';{$newline}var bark='bite';{$newline}" )
    <script>
    $jsCode</script>
    

    Result:

    <script>
    var bling='blang';
    var bark='bite';
    </script>
    
    0 讨论(0)
  • 2021-02-13 04:47

    In Velocity 1.4 neither newlines in strings works nor does the escapeTool.getNewline() exist. If you do not have the possibility to add anything to the context, here is a Velocity-only hack to generate arbitrary characters:

    #macro(chr $charCode $str)
      #set($str="0")
      #set($chars=$str.charAt(0).toChars($charCode))
      #set($str="")
      #foreach($char in $chars)
        #set($str="$str$char")
      #end
    #end
    
    #chr(10 $nl)
    
    First Line${nl}Second Line
    

    It uses Character.toChars() to convert the ASCII code 0x0A = 10 to a char[] which it then assembles into a string. This way one could generate any character such as

    #chr(129299 $nerd) ## U+1F913 => 0x1F913 = 129299
    $nerd
    ## outputs                                                                     
    0 讨论(0)
  • 2021-02-13 04:56

    If you are using Velocity 1.5 or later, you can also just put the new line in there:

    #set( $foo = "this has a 
    line break" ) 
    
    0 讨论(0)
  • 2021-02-13 04:57

    We had issues with newlines and ended up putting a property on the VelocityContext:

    VelocityContext ctx = new VelocityContext();
    ctx.put("newline", "\n");
    

    Then, wherever we needed to use a newline, we would reference the context variable:

    $newline
    

    We use this in cases where we need to replace newlines in a string with <br />.

    0 讨论(0)
  • 2021-02-13 05:00

    Are you using Velocity to generate HTML content? In that case remember that you need to use <br> not a newline.

    If you actually want a new line character you just put the actual new line character, i.e. press enter. There is no escape sequences like \n in Velocity.

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