[Ruby] evaluating Javascript within <%= %> within a template file
Laurel Fan
laurel.fan at gmail.com
Tue Aug 7 09:50:16 PDT 2007
On 8/7/07, Frank Schwieterman <fschwiet at gmail.com> wrote:
> One issue I see is that the <% %> enclosure is evaluated when the website
> is served, but "id_to_use" will not have a value until the Javascript is
> ran. I don't see any way for a <% %> enclosure to take a parameter. Maybe
> this is just not possible...
Right, it's not possible for the ruby code to "take a parameter" from
Javascript. I think the general idea that Jack is going for is that
you want ruby code that outputs Javascript that takes a parameter.
For example, this might be the Javascript that you want to end up
with:
var url = 'http://test.host/thing/edit/' + id_to_use + ''
In which case you might want what Jack suggested, something like:
var url = '<%= url_for :action => "thing", :id => "' + id_to_use + '"%>'
Assuming you don't drown in nested single quotes and double quotes,
what this does is trick url_for into putting the string ' + id_to_use
+ ' in place of where you'd normally have the integer id. So instead
of generating a url it generates something you can make into
Javascript code.
For this particular case it's pretty messy, since you can't really
duplicate all of the routing magic behind url_for in js (what happens
if you make pretty urls with the object name in them, etc).
If you want to do a lot of this sort of stuff, Rails has a lot of
javascript helper stuff like Prototype, RJS templates, scriptaculous
(and probably a lot more stuff that I don't keep up with because I
don't do a lot of this sort of stuff).
--
Laurel Fan
http://blog.gorgorg.org
More information about the Ruby
mailing list