0

I'm trying to create a webpage (using the play framework) which displays the user's name, date of birth etc. Where I am getting stuck is attempting to display a list of unknown size in an html page. I currently have:

@(currentUser : Profile)

@main("Profile") {
    <div>
        <h1><b>@currentUser.getFirstName() @currentUser.getLastName()</b></h1>
        <p>@currentUser.getDateofBirth</p>
        <b>Nationalities</b>
        <ul><p id="natInput"></p></ul>
        <script>
            for (var i = 0; i < "@currentUser.getNationalities().size()"; i++) {
                document.getElementById("natInput").innerHTML += "<li>" + "@currentUser.getNationalities().get(i)" + "</li>";
            }
        </script>
    </div>
}

Profile is a basic java class which only contains getters and setters, and .getNationalities returns a List. @Main is another html file which stores the base design of the website, not really relevant to this.

As you can see, I'm trying to use the .get method to loop through the list of nationalities for the user, but unfortunately the "i" variable used in the get is not recognised, as it is a javascript variable in html. Every other part of this code appears to work as expected, and the .get works when the "i" is replaced with an integer, such as 0 or 1.

Any ideas how I could get each individual element of this list? Any help would be greatly appreciated

1 Answer 1

2

The problem is that you are messing up different step of the page generation.

First of all we should clear out the processing steps from a render command in a Play controller to a fully rendered page in the browser.

Twirl is a template engine that allow you to generate HTML pages with Scala. This step is performed on server side, before the HTML page is sent to the browser. In this step the Javascript code is not being considered.

So the first step after the render command, the twirl template is picked and rendered, evaluating each Twirl/Scala instructions. This will generate an HTML file with no more Scala code.

This generated page is sent to the browser. Then the page is loaded into the browser and the Javascript code is evaluated as any other HTML page with JS.


This would explain why you are not able to render the page the way you are doing.

A proper way, if your page is static, is to use only twirl instructions to iterate over the array Twirl Template - Iterating

You should be able to rewrite your list generation like the following if getNationalities() method returns a Scala List

<ul>
@for(nationality <- currentUser.getNationalities()) {
   <li>@nationality</li>
}
</ul>
Sign up to request clarification or add additional context in comments.

Comments

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.