0
votes

I have this Play template, dynamicLink.scala.html...

@( urlWithQuotes: Html, id: Html, toClick: Html )

@uniqueId_With_Quotes() = {
    Html("\"" + (@id) + "_" + scala.util.Random.nextInt.toString + "\"")
}

@defining(uniqueId_With_Quotes()) { uniqueID =>
    <a id=@uniqueID class="dynamicLink" href=@urlWithQuotes> @toClick </a>

    <script><!--Do stuff with dynamic link using jQuery--></script>
}

It generates a special link with some Javascript. I render this link like so...

@dynamicLink(
    Html("@{routes.Controller.action()}"),
    Html("MyID"),
    Html("Click Me")
)

When I render it, I get...

<a id=
Html("\"" + (MyID) + "_" + scala.util.Random.nextInt.toString + "\"")
class="dynamicLink" href=@{routes.Controler.action()}> Click Me </a>

This is not what I want to render. I want to render this...

<a id="MyID_31734697" class="dynamicLink" href="/path/to/controller/action"> Click Me </a>

How do I make this HTML escape correctly?

* Take #2 - replacing Html params with String *

@(urlWithQuotes: String, id: String, toClickOn: String)

@uniqueId_With_Quotes() = {
    Html("\"" + (@id) + "_" + scala.util.Random.nextInt.toString + "\"")
}

@defining(uniqueId_With_Quotes) { uniqueID =>
    <a id=@uniqueID class="dynamicLink" href=@urlWithQuotes> @toClickOn </a>
    ...
}

With...

@dynamicLink2(
"@{routes.Controller.action()}",
"MyID",
"Click Me"
)

Renders...

    <a id=
    Html("\"" + (MyID) + "_" + scala.util.Random.nextInt.toString + "\"")
 class="dynamicLink" href=@{routes.Controller.action()}> Click Me </a>
    <script>
        ...
    </script>

* Changing Html to String didn't work *

* Note that " @uniqueId_With_Quotes() " expands into " Html("\"" + (MyID) + "_" + scala.util.Random.nextInt.toString + "\"") ". I want it to actually execute string concatenation. *

Also, this should be obvious, but I want each link and the accompanying jquery to be rendered with an ID that is unique to that link and I don't want the controller to have to worry about assigning these unique id's. My way of doing that is by appending a random number to each id (although it might just be better for the view to have a count). I need to have this stateful behavior in the view because I need "dynamicLink" to be totally transparent to the controller.

2

2 Answers

0
votes

Did you tried to use the variables as String types?

@( urlWithQuotes: String, id: String, toClick: String )
0
votes

I find the solution. You have to pass a Call object.

    @dynamicLink(
    ({routes.Controller.action()}),
    "MyID",
    "Click Me"
    )

Pass those parameters into...

@(urlNoQuotes: Call, id: String = "", toClickOn: String = "")

@uniqueId_With_Quotes() = @{
    Html("\"" + (id) + "_" + scala.util.Random.nextInt.toString + "\"")
}

@url() = @{
    Html("\"" + urlNoQuotes + "\"")
}

@defining( url() ) { processedURL =>
    @defining(uniqueId_With_Quotes()) { uniqueID =>
    ... 
    }
}

^ Now it works.