javavelocity

How to get Javascript Variable Content in to a Velocity variable?


I am using Polarion, which uses Velocity Template and thus javascript and html. A lot of the details don't really matter but I use

#set($currentId = "this.id")
console.log($currentId)
activityBox.innerHTML += ${currentId};

Which logs and correctly appends the right Id of the div im on right now. However if I try to invoke a function from my Java API it doesn't properly evaluate the variable $currentId

#set($currentWorkitem = $trackerProject.getWorkItem($!{currentId}))
console.log("$currentWorkitem")

it does call the function, but with the wrong argument. It uses "this.id" instead of the actual Id.

I know this most likely has something to do with the order in which velocity and javascript are evaluated, but I don't know if I can fix this. How can I properly put the value of a javascript expression inside my velocity variable?


Solution

  • It's your very first line which is wrong. You said it yourself, it's an evaluation order problem. this.id is unknown at the time velocity is evaluated, since Velocity rendering happens on the server, before Javascript evaluation in the browser.

    Velocity does generate code (HTML code or Javascript code) which is transmitted over the network to your browser, which interprets this code.

    You can write let someJavascriptVar = "${someVelocityVar}" because the browser will see `let someJavascriptVar = "Hello there".

    You cannot do the opposite, because the browser has not even received the Javascript code he's supposed to run, how would any Javascript variable mean something at this point?

    What you can do from Javascript is make another request to the server (using Ajax for instance), let Velocity on the server generate a new content, wait for this content in the browser (typically asynchronously using the fetch API), then use the values sent back from the server.

    In a nutshell, you need a new round-trip between the client and the server.