How to Keep Velocity Ouput to a Single Line while Spanning Multiple Lines in vm File

StackOverflow https://stackoverflow.com/questions/22974260

  •  30-06-2023
  •  | 
  •  

Question

I'm using a Velocity template to generate an e-mail. Within that e-mail, I want to create a mailto link that will look like this:

<a href="mailto:chris@abc.com,bob@abc.com?subject=My%20Subject%Line">Link</a>

I have this chunk of code that properly creates that link:

<a href="mailto:#foreach(${person} in ${people})${person.email}#if($foreach.hasNext),#end#end?subject=My%20Subject%20Line">Link</a>

That code works, but it's nearly impossible to read. I want to put some line breaks in there so that I'd have something more like this:

<a href="mailto:
    #foreach(${person} in ${people})
        ${person.email}
        #if($foreach.hasNext)
            ,
        #end
    #end
?subject=My%20Subject%20Line">Link</a>

I find that to be much easier to read, but Velocity will include all the whitespace into the output and causes the link that it produces to break.

Is there any way to format the code the way I want and tell Velocity to ignore all the whitespace throughout that segment?

Thanks!

Was it helpful?

Solution

A first option is to use comments:

<a href="mailto:#*
    *##foreach(${person} in ${people})#*
        *#${person.email}#*
        *##if($foreach.hasNext)#*
            *#,#*
        *##end#*
    *##end#*
*#?subject=My%20Subject%20Line">Link</a>

Another option is to add a pre-processing that will remove all indenting spaces and carriage returns.

Yet another is to do it as a post-processing.

The way to add this pre- or post- processing is dependent on the context in which you are using Velocity.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top