Question

I am currently working on cleaning up a little web app I've written in Mojolicious. As part of that cleanup I am separating out my javascript into the public directory from my html.ep files.

The problem I have though is I don't seem to be able to reference tag helpers any more, like 'url_for' or even referencing values in the stash such as '<% $stashvalue %>'.

Any idea's on how or if I can do this is very much appreciated.

cheers.

Was it helpful?

Solution 2

What I typically do is encapsulate most of my javascript in function calls or objects in pure javascript files. Then in my templates I include those pure javascript files and use the api that I built in those files from the template, interpolating the server-side variables into the arguments of the functions. You can peruse the code for Galileo to see several examples.

For example, see how this template passes stash values to this pure javascript file's functionality.

OTHER TIPS

The stuff in the public directory is served statically, optimally by your webserver, not by Mojolicious or Plack, so that file does not get processed by Mojolicious, thus <% $stashvalue %> not meaning anything.

A solution would be to embed those parts of javascript that need to access server side variables in the mojo templates - rather ugly, but less code to be written.

Another one would be to make an ajax call from your javascript files, when they are loaded, and get the values sent by the server - more elegant, but more code to be written.

Another one that I can think of, would be to move those javascript files under a folder that gets processed by Mojolicious and include them parameterized - in your html.ep file that needs that js file, do :

<script type="text/javascript" src="http://example.com/url/served/by/mojo/?param1=<% $stashvalue %>&param2=<% $stashvalue2 %>"></script>

And, in the controller that responds to /url/served/by/mojo/, render that js file, with the params replaced by the ones from the query. As an alternative, you could store/receive those params also on the session

As usually in Perl, there is more than one way to do it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top