Link to controller action in Play Framework 2.3

I'm working on a Play app and need to generate links in a mixed Scala-HTML representation that calls controller actions. I found this question a couple of years ago, similar to my situation, but the answers provided don't work for me.

The items are generated in a loop, so I can't manually insert the argument into the controller action, but nothing I've tried has worked. This is my line:

ID: @{var fhirID = <processing for ID>; <a href='@routes.Users.fhirUserDetails(fhirID)'>fhirID</a>}

      

The accepted answer to the question I linked earlier makes good use of this structure:

<a href='@routes.Application.show("some")'>My link with some string</a>

      

My problem here is twofold:

1) How can I pass the fhirID variable to the controller action? My generated link just has the text "fhirID" instead of the one generated by the first part of the instruction.

2) Is the @ routes.Users syntax correct? When I click on the generated link, it literally tries to render the page at / myapp / @ routes.Users.fhirUserDetails (fhirID)

I realize that I probably missed something very basic - thanks for any advice!

+3


source to share


1 answer


The problem is not with the syntax @routes

(which you completely fix), but in the case where the Twirl engine doesn't see where the code ends and HTML starts (or something like that ...)

The line you included, which has both a var

semicolon and a semicolon, made me suspect this, and I was able to reproduce the problem when I use this style.

My recommendation is to use a @defining

helper
, not var

to get a scoped variable to use in your links, like this



ID: @defining(<processing for ID>) { fhirID => 
  <a href='@routes.Users.fhirUserDetails(fhirID)'>fhirID</a>
}

      

You can nest blocks @defining

as deeply as you like if needed, although it's probably better to make the call to a reusable block if there is a lot of logic. I think this style makes templates more readable and also somehow more like "real Scala" :-)

+2


source







All Articles