Reputation: 28971
I'd like to be able to use some of rails' view and form helpers, such as <%= image_tag .. %>
or <%= select_tag .. %>
inside my javascript templates. I read this thread that suggested pre-rendering the erb as a string in some javascript variable and then calling it from the template (it'll have to be available before the js template is called). So I could do something like this:
<script type="text/javascript">
var ViewHelpers = {
CountrySelect: "<%= select_tag "person[country_id]", options_from_collection_for_select(Country.all, "name", "id"), :prompt => '-Country-' %>"
};
</script>
And then call it from my eco template (rendered later):
...
<p>
<label for="person_country_id">Country</label>
<%= ViewHelpers.CountrySelect %>
</p>
...
However, I seem to be unable to load it both as part of the view or using the asset pipeline:
(saved in app/assets/javascripts/views/people/view_helpers.js.erb)
//= require ./views/people/view_helpers
(saved in app/views/people/view_helpers.js.erb)
<%= render :template => 'people/view_helpers' %>
Am I approaching this problem completely wrong or have I missed something? thanks.
Upvotes: 1
Views: 3168
Reputation: 32436
Yes, it's possible. You can even use it with partials:
update_js.js.erb:
$('#element').html('<%= escape_javascript(render(:partial => @partial, :locals => {:my_var => @item })) %>');
in controller you should have format js
:
respond_to do |format|
format.js do
render :update_js do |page|
page.replace_html "element", :partial => @partial
end
end
end
if you want to call this js with AJAX simply pass :remote => true
to your link
<%= link_to 'replace content', item_path(@item), :remote => true %>
Upvotes: 1