Ask A Question

Notifications

You’re not receiving notifications from this thread.

How do I send send a erb template as a string in a json response?

Morgan asked in Rails
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:

  1. Users saves section.
  2. Section#update updates section
  3. Responds with json with something like: { resp: { data: @section: template: “ERB STRING”} }
  4. Page editor updates the iframes section with the updated resp.template
  5. 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. 
Reply
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
# 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!
Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 87,563+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.