简体   繁体   中英

adding parameter values inside of parenthesis while using scala.html

i would like to add dynamic parameter values (not sure if i can call it like this) to the url in my scala html.

Using javascript, I get userId first and then would like to pass it to @routes.adminController.auth(userId).

Here is my source code,

<script type="text/javascript">
function checkboxChecked() {
  var checkbox = $('td > input:checked').length;

  if(checkbox == 1){
    var $checked = $('td > input:checked');
    var userId = $checked.parent().next().text();

    ** I would like to add below and make it work**
   //location.href = @routes.AdmnTask.user_set(userId)

  } else {
    alert("Please select 1 User ID to proceed.")
  }

};
</script>

After a few attempts, I noticed that I am not able to set some random variable and put into location.href as below.

var link = "@routes.AdmnTask.user_set(userId)"
location.href = link

Could anyone give me a help with this issue please?

Thank you in advance.

As I said in the comments, you can't use a Javascript variable inside a Scala function, since the Scala is executed server-side and the Javascript client-side.

There's a workaround, though.

If your @routes.AdmnTask.user_set( ... ) gives you an URL with the parameter at the end, like http://example.com/userSet/1 or http://example.com/userSet?id=1 , you could create a function that transforms this URL into a more generic one :

/**
 * Gets the base URL for a given route
 *
 * @param  url Call - The route called with the parameter 0
 * @return The URL base String.
 */
public static String baseUrl(play.api.mvc.Call url){
    return url.toString().substring(0, url.toString().length() - 1);
}

This function will cut off the last character from your URL String, so that you can use it in your Scala template.

Then, all you need to do in your Scala / Javascript is :

location.href = '@yourClass.baseUrl(routes.AdmnTask.user_set(0))' + userId

EDIT: Here is the Scala version of the function above :

def baseUrl(url: play.api.mvc.Call): String = {
  url.toString.substring(0, url.toString.length - 1)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM