如何让 Sinatra 以 HTML 形式提供 Markdown 以及以纯文本形式提供源代码?
我正在使用 Sinatra 和 Heroku 构建一个简单的“笔记”网站。我使用 Markdown 编写笔记,并在 Sinatra 中使用 rdiscount gem 将它们转换为 HTML。因此,对 /foo 的请求将提供模板 /views/foo.md,转换为 HTML
我还希望能够将 Markdown 源作为纯文本文件提供。因此 /foo/source (或类似的东西)将以纯文本形式提供 /views/foo.md 。
我尝试过使用 ERB 但它最终只想提供 /views/foo.erb 服务。
这是我当前的应用程序:
require 'sinatra'
require 'rdiscount'
set :markdown, :layout_engine => :erb
get '/' do
markdown :index
end
get '/:topic' do
markdown params[:topic].to_sym
end
I'm building a simple "notes" site using Sinatra and Heroku. I write my notes up using Markdown and use the rdiscount gem to convert them to HTML in Sinatra. So a request for /foo would serve up the template /views/foo.md, converted to HTML
What I'd also like to be able to do is serve up the Markdown source as a plain text file. So /foo/source (or something similar) would server up /views/foo.md as plain text.
I've tried using ERB but it just ends up wanting to serve /views/foo.erb.
Here is my current app:
require 'sinatra'
require 'rdiscount'
set :markdown, :layout_engine => :erb
get '/' do
markdown :index
end
get '/:topic' do
markdown params[:topic].to_sym
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
简短的回答:使用 File.read 来吸收文件的内容,然后用它做你想做的事情:
长的回答:Sinatra 可能会因为点、冒号和文件类型而变得有点愚蠢,所以你可能有夺取参数的控制权。以下(有效!)Sinatra 应用程序可能有助于演示。
Short answer: use
File.read
to suck in the file's contents, then do what you want with it:Long answer: Sinatra can get kind of goofy with dots and colons and file types, so you may have to wrest control of the parameter. The following (working!) Sinatra app may help demonstrate.
经过更多的搜索,我设法使用 send_file:
但我相信有一个更优雅的解决方案,所以现在暂时保留这个问题。
With a little more searching I managed to get it working using send_file:
But I'd like to believe there's a more elegant solution out there, so leaving the question open for now.
您可以尝试使用
str
模板:唯一需要考虑的是,它会尝试像处理字符串一样插入值 - 换句话说,它会尝试替换
#{foo}
与foo.to_s
。这可能是理想的,也可能是不理想的。免责声明:我不确定它会起作用,我必须通过查看 Tilt< 的源代码来推断此功能/a>,我还没有测试过。
编辑:恐怕这行不通。可以这样定义 str 方法:
Tilt 引擎尝试查找名为“foo.str”的视图,而不是使用“foo.md”。我还尝试将“md”注册为 StringTemplate 的有效扩展,但它不起作用(我要么将 markdown 渲染为字符串,要么遇到与以前相同的错误。
抱歉。
You can try using the
str
template:The only thing to take into account is that it'll try to interpolate the values like it would do with a string - in other words, it'll try to replace
#{foo}
withfoo.to_s
. This might or might not be desirable.Disclaimer: I'm not sure it'll work, I had to deduce this functionality by looking at the source code of Tilt, and I haven't tested it.
Edit: I'm afraid that doesn't work. It's possible to define the str method like this:
The Tilt engine tries to find a view called 'foo.str' instead of using 'foo.md'. I also tried registering 'md' as a valid extension of StringTemplate, but it didn't work (I either got the markdown rendered as a string, or I had the same error as before.
Sorry.