1

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.

2
  • 1
    Have you read this answer? stackoverflow.com/questions/7451517/… I think there's some useful information regarding your problem. Commented Nov 13, 2012 at 12:34
  • No, missed that one, and it seemed to do the trick - I was missing an include to ActionView::Helpers. Thanks! Commented Nov 13, 2012 at 19:16

1 Answer 1

1

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 %>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.