2

I'm new to the Play framework (1.2) but I was wondering and hopefully I phrase this question correctly....I have a Play variable which stores which section ("_section") of a page the user is currently viewing. Is there any way to access that variable from a .js function?

UPDATE:

You can store objects for js as well from play:


    <script type="text/javascript">
          window.mytestarray = new Array();
     </script>



       #{list 0..links.size()-1, as:'i'}



   {%
    router = play.mvc.Router;
    url = router.reverse(_section + '.' + links[i]).url;
   %}


      <script  type="text/javascript">
           window.mytestarray.push("${url}")
      </script>


   <li js_sub_nav_name="${ _section}" >  <!-- MC class="#{if i == 0}first#{/if}"-->
   <a href="${url}" class="${lines[i]}#{if _page == links[i]} active#{/if}">&{'header.nav.'+_section+'.'+links[i]+'.html'}</a>

   </li>
  #{/list}
  </ul>
 #{/if}

2 Answers 2

3

You can create a javascript global variable inside your view file, and access that variable from other javascript files:

#my view
...
<script type="text/javascript>
window._section = "${_section}";
</script>

Then from within a javascript file:

if (_section == ...)
Sign up to request clarification or add additional context in comments.

4 Comments

Yes exactly what I was trying to do! Just one thing; there is a syntax error in your code: should be: <script type="text/javascript"> (Missing " at end of 'javascript')
Also can you access local play variables and objects as well? For instance in this play code can I store 'router' and 'url' for later reference in Javascript? #{list #{list 0..links.size()-1, as:'i'} {% router = play.mvc.Router; url = router.reverse(_section + '.' + links[i]).url; %}
One more thing: if _section is updated in play code then the corresponding js variable is not updated...any way around that?
Found you can store objects --- in an array for example: {% router = play.mvc.Router; url = router.reverse(_section + '.' + links[i]).url; %} <script type="text/javascript"> window.mytestarray.push("${url}") </script> <li js_sub_nav_name="${ _section}"
3

Use html5 data attributes, like:

<div id="yourSection" data-section="${_section}">
...your section contents...
</div>

2 Comments

Any chance you can store an object in data-section and not just a string?
if you stretch it a bit, you could maybe store a json string that you can convert easily to a javascript object, or if you stretch it a bit more, you can serialize your object however you want and have a javascript version to deserialize it. I've never needed to do anything like that.

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.