Skip to content

Commit

Permalink
Merge pull request web2py#351 from benlawraus/helperInJS
Browse files Browse the repository at this point in the history
added Helpers in Javascript as written by Anthony
  • Loading branch information
mdipierro authored Mar 27, 2017
2 parents 339ef39 + df31197 commit 3a058fe
Showing 1 changed file with 24 additions and 1 deletion.
25 changes: 24 additions & 1 deletion sources/29-web2py-english/05.markmin
Original file line number Diff line number Diff line change
Expand Up @@ -1889,8 +1889,31 @@ we get:
Hello World!!!
<div class="sidebar">
my default sidebar
my new sidebar!!!
my new sidebar!
</div>
</body>
</html>
``:code


``javascript``:inxx
### 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>
``:code

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>
``:code

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

0 comments on commit 3a058fe

Please sign in to comment.