astriffe
astriffe

Reputation: 172

How to access playframework's controller data in view javascript?

I have a javascript application where I'd like to add autocompletion to a form. Therefore, I render an array containing all available names in the controller so the array is available in the view (html).

$(function() {${"id"}.autocomplete({source: how to get the data here??}); });

Now I'd like read this data into a variable so I can use it in my javascript for the autocompletion... Can anyone tell me how to achieve this?

TIA

- astriffe

Upvotes: 1

Views: 575

Answers (1)

Felipe
Felipe

Reputation: 1300

You need this data to be serialized in JSON, that when printed in javascript will be interpreted as javascript.

To help you with that, play! has Google JSON library

An example how could you achieve this is:

<% def gson = new com.google.gson.Gson(); %>
$(function() {${"id"}.autocomplete({source: ${gson.toJson(playVariable)} }); });

But this is ugly code, it would be better to use template extensions to achieve this

Upvotes: 4

Related Questions