hybrid
hybrid

Reputation: 3968

How to render html file as haml

I'm fairly new to ruby and working on building a front-end styleguide that has html snippets I'd like to render as haml into a pre tag. I'm building a helper for middleman and have figured out how to read an HTML file and output its contents. Now I'd like to convert the html to haml and output that.

Looking around it seems like the html2haml gem is what I want to use, though the doc on that gem seems to only cover using it on the command line, whereas I'm trying to add this functionality to a helper.

Here is what I have so far for a helper

helpers do
  def render_snippet(page)
    p1 = ("<pre><code>").html_safe
    p2 = File.read("source/"+"#{page}")
    p3 = ("</code></pre>").html_safe
    p0+p1+p2+p3
  end
end

Here is how I'm using the helper

= render_snippet "partials/examples/typography/elements.html"

Upvotes: 2

Views: 946

Answers (2)

hybrid
hybrid

Reputation: 3968

I ended up working on this some more and ended up with the following:

def render_html2haml(file)
  templateSource = preserve(File.read("source/"+"#{file}"))
  haml = Html2haml::HTML.new(templateSource, {:erb => nil})
  content_tag(:pre, content_tag(:code, haml.render))
end

Upvotes: 0

MilesStanfield
MilesStanfield

Reputation: 4649

To answer your question, this is how you can make a helper to use html2haml gem outside the terminal shell commands

# some_view.html.erb
<%= render html_2_haml("home/my_partial.html") %>


# app/helpers/application_helper.rb    
module ApplicationHelper
  def html_2_haml(path)
    file_name = path.split("/").last
    path_with_underscore = path.gsub(file_name, "_#{file_name}")
    system "html2haml app/views/#{path_with_underscore} app/views/#{path_with_underscore}.haml"
    "#{path}.haml"
  end
end

Now i'd like to say this definitely will not work in production (as it's dynamically creating a new file and hosting services like Heroku just won't allow that) but if your just making yourself a development helper for this-and-that then perhaps this could be helpful to you.

Upvotes: 1

Related Questions