简体   繁体   中英

Using Rails' view helpers inside javascript templates

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:

view_helpers.js.erb

<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):

edit_person.jst.eco

...
<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:

Asset Pipeline: application.js

(saved in app/assets/javascripts/views/people/view_helpers.js.erb)

//= require ./views/people/view_helpers

OR

ERB template: views/people/index.html.erb

(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.

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 %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM