Velocity Templates - New Line

后端 未结 6 1188
醉话见心
醉话见心 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: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 

提交回复
热议问题