How do I send send a erb template as a string in a json response?
I have a page editor that shows the user a live preview of their changes as they make them, but I’m having trouble working out how to do this with erb templates.
In my previous non rails version, I simply synced the changes via a redux store which allowed react to instantly render the changes, but I would prefer to keep erb templates for the rails version which means I need to find another solution.
So far I have the page editor rendering a list of page sections that belong to the page in a column on the left and the actual page rendered in an iframe on the right.
I am currently updating the individual elements in the iframes page sections with::
updateSection: (section) => { const iframe = document.getElementById('ifameId') const innerDoc = (iframe.contentDocument) ? iframe.contentDocument : iframe.contentWindow.document; const selected_section = innerDoc.getElementById(section.id) selected_section('[data-page-setting="title"]').innerHTML = block.title },
Which is ok for the live updating but I would like to re-render the current sections template whenever the changes are persisted to the database (when a user clicks save or they click on another section to edit )
Something like:
- Users saves section.
- Section#update updates section
- Responds with json with something like: { resp: { data: @section: template: “ERB STRING”} }
- Page editor updates the iframes section with the updated resp.template
- Page editor updates the form fields with resp.data
From what I can see render_to_string would allow me to send the erb template as a string but I can't figure out how to get it working.
Hey Morgan,
I haven't had a chance to play with this yet, but I'll be needing to for a project here soon. What I had bookmarked to come back to when I started was https://coderwall.com/p/ov8eha/render-an-html-partial-inside-a-json-request
Here, mbillard suggests this approach:
helpers/application_helper.rb
I haven't had a chance to play with this yet, but I'll be needing to for a project here soon. What I had bookmarked to come back to when I started was https://coderwall.com/p/ov8eha/render-an-html-partial-inside-a-json-request
Here, mbillard suggests this approach:
helpers/application_helper.rb
# execute a block with a different format (ex: an html partial while in an ajax request) def with_format(format, &block) old_formats = formats self.formats = [format] block.call self.formats = old_formats nil end
controllers/your_controller.rb
def controller_action with_format :html do @html_content = render_to_string :partial => 'path/to/view', :locals => { /* any locals needed in the view */ } end render :json => { :html_content => @html_content } end
Hope it can be of some help!