Home > Software engineering >  Rails: render HTML from Nokogiri without template
Rails: render HTML from Nokogiri without template

Time:10-21

I'm trying to write a controller method (show) which renders HTML without using a template (to preview an email without styles, etc):

class EmailDownloadsController < ApplicationController
  before_action :set_email_download, only: %i[create show]

  def create
    send_data(@html, filename: "#{@document.safe_title}.html")
  end

  def show
    render @html.to_s
  end

  private

  def set_email_download
    @document = Document.find(params[:id])
    @document.parse_email_vars

    @html = Nokogiri::HTML(@document.email_campaign_version)
  end
end

I can't figure out how to render it without referring to a view (which comes with its own <html> and <head> tags). Anyone have any experience here?

The above code returns this error:

Missing template <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" style="min-height: 100%; background-color: #f3f3f3;">
...

CodePudding user response:

Ah, it's render inline:.

The render method can do without a view completely, if you're willing to use the :inline option to supply ERB as part of the method call. This is perfectly valid:

render inline: "<% products.each do |p| %><p><%= p.name %></p><% end %>"

Docs.

  • Related