Ruby Sinatra嵌入erb部分外部HTML文件

时间:2019-02-11 22:43:22

标签: ruby sinatra embed erb

我需要在我的网站上保存一份“购买合同”类型的报告。我正在使用Sinatra文件中的erb来传递内容。当人们注册各种项目时,我想通过电子邮件发送当前报告(版本会更改)。

我想我可以将它以某种格式存储在数据库或外部文件中,所以我可以同时做这两个事情:

  • 将其导入erb文件中以在网络上展示
  • 在电子邮件中使用它,使其以文本格式可读

因此,基本上我需要使用尽可能基本的格式,但必须将其转换为HTMLerb)和文本。

此文件的格式有哪些选项?以及如何将其转换为HTML?我看过markdown,发现gems可以转换为文本,效果不是很好。看到它需要纯文本以及HTML,我对如何完成此工作有点迷惑。

文件摘要

Privacy Policy
Updated Feb 20, 2019

Website.com (“Website”) is a private business. In this Privacy Statement the terms “we” and “our” refer to Website. This Privacy Statement explains Website’s practices regarding personal information of our users and visitors to this website (the “Website”), as well as those who have transactions with us through telephone, Internet, faxes and other means of communications.

Website’s Commitment to Privacy
At Website, we are committed to respecting the privacy of our members and our Website visitors. For that reason we have taken, and will continue to take, measures to help protect the privacy of personal information held by us.

This Privacy Statement provides you with details regarding: (1) how and why we collect personal information; (2) what we do with that information; (3) the steps that we take to help ensure that access to that information is secure; (4) how you can access personal information pertaining to you; and (5) who you should contact if you have questions and concerns about our policies or practices.

2 个答案:

答案 0 :(得分:1)

解决方案:将文件另存为HTML,并使用该gem转换为text

https://github.com/soundasleep/html2text_ruby

如果HTML很简单,就可以正常工作。

剩余:仍然存在将HTML文件用作partial的问题。

已解决

@text = markdown File.read('views/privacy.md')

因此将源文件存储为markdown文件,该文件可以转换为HTML。当我需要email版本时,我需要使用HTML gem转换为text,然后转换为HTML2texthttps://rubygems.org/gems/html2text

答案 1 :(得分:0)

据我了解,您有一部分文本(存储在数据库或文件中,实际上并不重要),并且您想要:

  • 通过网页将其保存为HTML格式
  • 通过电子邮件将其简单发送

假定标准的Sinatra项目布局,其中views目录位于项目目录中,例如

project-root/
  app.rb
  views/

以及在app.rb中传递文本的途径:

get "/sometext" do

end

如果将erb模板放在views目录中,并且在路由的最后一行调用erb模板渲染器,则应该获得HTML格式的输出。例如

project-root/
  app.rb
  views/
    sometext.erb # this is the erb template

在Sinatra应用中

# app.rb
# I'm assuming you've some way to differentiate
# bits of text, e.g.
get "/sometext/:id" do |id|
  @text = DB.sometext.getid id # my fake database call
  erb :sometext # <- this will render it, make it the final statement of the block
  # make sure @text is in the template
  # else use locals, e.g.
  # erb :sometext, :locals => { text: @text }
end

现在,当用户访问http://example.org/sometext/485995时,他们将收到HTML。通过网站或您选择的其他方法可以触发通过电子邮件将文本发送给用户。