Ducaz035
Ducaz035

Reputation: 3132

Accessing value by javascript Play Framework/Scala

First of all I am using Play framework with scala.

I am creating a graph and with the node id I would like to show some information at the same page.

In order to do that, first I need to get node.name but for some reasons @node.name function is not working. When searching for it I learnt that it's because play is server-side and js is client-side. However I need to get the data somehow.

I also cannot access:

var html = "<h4>" + node.name + "</h4><b> connections:</b><ul><li>"

How can I access this through the view?


My second question is after reaching the js node.name, I need to access to controller and do the same action one more time but this time with the new node.name .


View Part:

onClick: function(node) {
  @node.name
}

Upvotes: 0

Views: 2208

Answers (1)

Jens Egholm
Jens Egholm

Reputation: 2710

1) Is this code in your controller? And are the node variable in scope? If so this should be perfectly legal code, since it will be evaluated as pure scala.

2) The templates are a different story however. You probably know they parse everything as normal html, unless escaped. To use a variable you have to bring it into scope by either:

  • defining a 'constructor' for the template at the absolute beginning of the file:

    @(node : Node)

    ...

    @node.name // later in the file

See http://www.playframework.com/documentation/2.0/ScalaTemplates

  • or define a variable inside the template:

    @defining( Get.node.from.somewhere ) { node =>

        @node.name
    

    }

See Play! framework: define a variable in template?

If you did either of the two, you should have no problem accessing the node variable. Even in scripts. But note that external scripts does not have access to the same variables. It is thus very common to use inline scripts or import it as another template if you need to access a variable from JavaScript.

Edit: I've made a gist of a template, controller and routes file: https://gist.github.com/Jegp/5732033

Upvotes: 2

Related Questions