Home Use erb partials, in Rails, to append the DOM using JavaScript - not hitting controller
Reply: 2

Use erb partials, in Rails, to append the DOM using JavaScript - not hitting controller

Jonathan Bowman
1#
Jonathan Bowman Published in 2017-12-07 20:43:49Z

I have a form that has a variable number of line items, each having the same inputs and icons and lots of other elements. I have a _line_item.html.erb partial that gets used in a loop in the view to show existing line items.

I also have a button, at the bottom, that when clicked will add a new, blank line item to the page. Doing so, however, doesn't hit the controller and happens completely client side. Currently, I just have a variable in my javascript that is a big string equal to the same HTML in the partial. I have to edit and maintain the erb partial and the javascript string separately, though.

This is all kind of ugly, and not at all DRY, so I was wondering - is there any way to leverage the HTML present in the erb partial for appending new line items, WITHOUT having to hit the controller first? Or, is there a better client-side way of handling appending reusable blocks of HTML?

Also, cloning is not an option since at some point the user could remove all their line items. I guess I could leave a hidden one in the DOM somewhere, rendered via the erb partial, but that also feels not great.

jvillian
2#
jvillian Reply to 2017-12-07 21:00:09Z

You could do it something like:

  • add a new form at the end of your line_item list (rendered when you are rending the list) that is hidden via display: none in your css
  • when you click the add button (or whatever it's called), show the new form (and probably hide the add button). For the form, I like to use a slideDown() function
  • when the user fills in the form and clicks submit (or however you submit the form), then do your create ajax call to the server. In your controller, render _line_item.html.erb
  • .on 'ajax:success', append the line_item html to your list (maybe sorting, if that floats your boat), re-hide your new form (similar to above, I use slideUp()), and re-show your add button.
Daniel Westendorf
3#
Daniel Westendorf Reply to 2017-12-07 21:03:03Z

What you're doing is somewhat equivalent to what most implementations do.

Some implementations store the HTML in a <script type="text/html"> like tag, which may be a bit less painful for the updating of templates than maintaining a gigantic HTML string.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.332639 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO