kino
kino

Reputation: 21

Handling repeated values in template

the documentation says I can use @repeat for lists defined in forms.

http://www.playframework.com/documentation/2.1.0/JavaFormHelpers bottom of the page.

This might be totally stupid question... Can I use something similar for Map?

right now I have a helper class which consist, String key and String value. It works, but I have some logic in template. In my opinion that is not good...

edit: more info

suppose I have

class Article {
  ...
  Map<String, String> resources;
  ...getters, setters...
}

I call view to deal with form

return ok(form.render(Form.form(Article.class)));

in form.scala.html

@for((key, value) <-formArt("resources")) { 
    @key, @value
}

gives me error:

value map is not a member of play.data.Form.Field 

which makes complete sence, because it is not map anymore, but formField. There is helper in scala to deal with List, but I have no idea how to make helper to deal with Map. (if I try anything similar, for example use @repeat helper, gives me same error)

for those who are asking what is in Field.value

{value1=key1, value2=key2 ...}

Upvotes: 2

Views: 1024

Answers (1)

biesior
biesior

Reputation: 55798

If you want just to iterate the Map you can do that with @defining() and @for():

public static Map<String, Object> myMap() {
    Map<String, Object> myMap = new HashMap<>();
    myMap.put("name", "John");
    myMap.put("secondName", "Doe");
    myMap.put("age", 23);
    return myMap;
}

view:

@defining(Application.myMap()) { myMap =>

    Hello @myMap.get("name") @myMap.get("secondName")!
    <br><br>

    All entries of the map: <br>
    @for(entry <- myMap.entrySet()){
       Field <b>@entry.getKey()</b> has value: @entry.getValue() <br>
    }

}

Upvotes: 0

Related Questions