Javascript in views

Helpers can be used within external code by placing it in a template and then including the template where needed. For example, if some javascript code is in a file “/views/my.js”, then it can be included in a view file:

  1. <script>
  2. {{include 'my.js'}}
  3. </script>

However, this will be inefficient if there are many lines of javascript code but only few lines of dynamically generated web2py content such as helpers. An alternative is to define the dynamically generated web2py variables in one block of javascript in the template, and then load a static javascript file that simply refers to those variables (this is how “web2py_ajax.html” works — it defines several JS variables, which are then used by “web2py.js”). So, in the view file:

  1. <script>
  2. var someVar = "{{=T('some phrase to be translated')}}";
  3. var someURL = "{{=URL('default', 'myfunction')}}";
  4. </script>
  5. <script src="{{=URL('static', 'js/my.js')}}"></script>

or equivalently using the web2py ASSIGNJS helper:

  1. <script>
  2. {{=ASSIGNJS(someVar = T('some phrase to be translated'),
  3. someURL = URL('default', 'myfunction'))}};
  4. </script>
  5. <script src="{{=URL('static', 'js/my.js')}}"></script>

then in “my.js”, someVar and someURL can be used as normal javascript variables.