1

I am working in Play framework and I need to use Java array inside Javascript.

I tried the following -

var jsarray = ${javaArray};

Where javaArray is the array in the Java controller, being rendered to the HTML view.

But, it is not working. Can anyone please help me on this?

1 Answer 1

3

Don't forget you're not passing variables... You're writing javascript code

So, you have to make your array rendering nicely for Javascript

var jsArray = [%{javaArray.eachWithIndex{it,idx->
                 }%
                 ${it}${(idx<javaArray.size()-1)?",":""}
                 %{
                 }
                 }%]

Use something that fits with your template engine. You have to iterate through your array then prints out the values on the view

PS : I've used the Groovy notation...

Sign up to request clarification or add additional context in comments.

3 Comments

I don't know if Play/Scala will do it automatically with the .each function, but you need to comma separate each array value.
I was editing the post to say that... You should test the end of the array to not add the last comma thanks for spotting :-)
Thanks a lot... It worked for me... Since I am using a string array, I need to modify the above as "${it}" - (added "")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.