0

I want to access model items by index from JavaScript into a Play Framework template:

<script type="text/javascript" charset="utf-8">
    window.onload = function()
    {
        var cl = ${colors.size()};
        int i = 0;
        for (i=0;i<cl;i++)
        {
            labels = labels + "${colors.name.get(i).escapeJavaScript().raw()}";
        }
    }
</script>

My problem is that this loop throws an exception:

IndexOutOfBoundsException : Index: 12, Size: 4

Nota 0: model = Color.

Nota 1: the size is 4.

Nota 2: if I test with a fixed number instead of variable i it is ok, but this is not what I need.

Cannot get why it does not work.

1
  • 1
    Is there any chance you're mixing up Java and JavaScript? You're using both var and int, and assuming that the JavaScript i is available in Java. Commented Oct 3, 2011 at 14:28

1 Answer 1

3

You try to use Groovy inside a Javascript loop which is wrong.

Remember your Groovy code (inside ${}) is evaluated by the Play templating on the server side and result of an HTML page returned to the client, and the Javascript is evaluated on client side (by the browser, not on your server).

maybe you want to do something like :

<script type="text/javascript" charset="utf-8">
window.onload = function()
{
    labels = [#{list colors.name}"${_.escapeJavaScript().raw()}"#{if !_isLast},#{/if}#{/list}];
}

which is still dangerous if you don't understand what it does,

prefer using a simple AJAX request and the renderJSON method for dynamic loadings.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.