Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Playframework: Elegant way to pass values to javascript

Does anyone have an elegant solution to pass server values to javascript (that is not inline) in playframework? just like ${x} or &{'x'} inside html

Currently I can think of

  <script type="text/javascript">
     var x= ${x};
  </script>
  <script src="/public/javascripts/jsThatUsesX.js" type="text/javascript" ></script>

I'm thinking there is a better solution from play

like image 380
roshan Avatar asked Jul 13 '11 00:07

roshan


2 Answers

It's not pretty, but that's the way I always end up doing it.

If the values that you're passing to JavaScript describe something in the DOM, you might consider using HTML 5 data attributes to place that information in the HTML. Then you can retrieve it with getAttribute. e.g. If your page is a blog post and you need to store the post ID you could use

<div class="post" data-post-id="77">
   ...
</div>

That way the data is separated out from the logic and you don't need to inline any JavaScript. You could also use a hidden form field.

like image 57
takteek Avatar answered Sep 18 '22 12:09

takteek


What's wrong with that? I found myself doing things like

<script>
   var trades = [${_trades.collect {models.Trade t -> t.price}.join(", ")}];
   // ...
</script>

I like it the groovy way ;)

like image 41
André Pareis Avatar answered Sep 21 '22 12:09

André Pareis