Question

I need to get a javascript variable in my template ( play framework 1.2.6) :

#{extends 'main.html' /}
#{set title:'My Resa V.1' /}
<div id="content">

<div id="draggable" class="ui-widget-content">
    <p>Drag me around</p>
</div>
<div id="circle"> <center>table 1</center></div>
</div>

<script>
    $(function() {
        $( "#draggable" ).draggable();
        $( "#circle" ).draggable({
                    stop: function(event, ui) {
                    var circle = $(this).position();
                  var position= circle.top;
                }
            });
    });
    </script>

I want to get var position= circle.top;. Thanks

Was it helpful?

Solution

The main reason of your problem is that the play template engine is executed on a server side, and the javascript code is executed at the client side (i.e. into the web browser).

So if you want to add variable from the server state (from java), you should "write" (inject) your javascript code at server side, so it will be present when the page will load to the client, and thus can be executed there.

In order to do this, first you need to send your circle variable from the controller to the view using the following code:

Circle circle=getYourCircle();
render("path/to/your/view",circle);

Next, in your view file just replace the line where the position is initialized:

var position= ${circle.top};

Again, the ${} expression will be evaluated on the server and the value will be written into the body of the response that will be returned to the client. So, in this case if your circle has value for its top property equal to 40, the browser will get:

var position= 40;

for the corresponding line.

For the other way around (i.e. reading a javascript variable in the template) is not possible, unless you make a request to the server (for instance by using some of the jQuery.ajax variants), and send the value of the javascript variable.

The request should be accepted by a controller, and the value for the variable should be delegated to the view (same procedure as in the first code snippet). Even then the play template engine will be able to access the "javascript" variable (which now is request scope variable) and make additional transformations to it.

I hope this helps :)

OTHER TIPS

thanks! I finally used Ajax mechanism:

...
var allPosition='';
                for (var m in map){
                allPosition+= m +'-' + map[m].top + '-' + map[m].left+'/';
                }
 var updateUserRoute = #{jsRoute @Application.saveDisposition() /}
...

function callAjax(updateUserRoute,allPosition){

            $.ajax({
             url: updateUserRoute.url(),
             type: updateUserRoute.method,
             data:{ positionTables: allPosition}
            });

            //.done(function( msg ) {
         // alert( "disposition des tables sauvegardé" );
        //  });
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top