如何将html文件呈现为haml

如何将html文件呈现为haml,html,ruby,haml,helper,Html,Ruby,Haml,Helper,我是ruby的新手,正在构建一个前端样式指南,其中包含html片段,我希望将其作为haml呈现到一个pre标记中。我正在为middleman构建一个助手,并且已经了解了如何读取HTML文件并输出其内容。现在我想将html转换为haml并输出它 环顾四周,我似乎想使用gem,尽管gem上的文档似乎只涉及在命令行上使用它,而我正试图将此功能添加到助手中 这是我到目前为止为一个助手所做的 helpers do def render_snippet(page) p1 = ("<pre&

我是ruby的新手,正在构建一个前端样式指南,其中包含html片段,我希望将其作为haml呈现到一个pre标记中。我正在为middleman构建一个助手,并且已经了解了如何读取HTML文件并输出其内容。现在我想将html转换为haml并输出它

环顾四周,我似乎想使用gem,尽管gem上的文档似乎只涉及在命令行上使用它,而我正试图将此功能添加到助手中

这是我到目前为止为一个助手所做的

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
“”.html_安全 p0+p1+p2+p3 结束 结束 下面是我如何使用助手的

# 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

为了回答您的问题,以下是如何让助手在终端shell命令之外使用html2haml gem

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
#some_view.html.erb
#app/helpers/application_helper.rb
模块ApplicationHelper
def html_2_haml(路径)
文件名=path.split(“/”).last
path_,带下划线=path.gsub(文件名,“{file_name}”)
系统“html2haml app/views/#{带下划线的路径}app/views/#{带下划线的路径}.haml”
“#{path}.haml”
结束
结束

现在我想说的是,这在生产中肯定不会起作用(因为它会动态创建一个新文件,而像Heroku这样的托管服务就是不允许这样)但是,如果你只是让自己成为这方面和那方面的开发助手,那么这可能会对你有所帮助。

我在这方面做了更多的工作,最后得出以下结论:

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