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:
<script>
{{include 'my.js'}}
</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:
<script>
var someVar = "{{=T('some phrase to be translated')}}";
var someURL = "{{=URL('default', 'myfunction')}}";
</script>
<script src="{{=URL('static', 'js/my.js')}}"></script>
or equivalently using the web2py ASSIGNJS
helper:
<script>
{{=ASSIGNJS(someVar = T('some phrase to be translated'),
someURL = URL('default', 'myfunction'))}};
</script>
<script src="{{=URL('static', 'js/my.js')}}"></script>
then in “my.js”, someVar
and someURL
can be used as normal javascript variables.