Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use Mojolicious tag helpers in external JS files?

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.

like image 321
user1768233 Avatar asked Jan 14 '23 00:01

user1768233


1 Answers

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.

like image 161
Tudor Constantin Avatar answered Jan 19 '23 11:01

Tudor Constantin