How do I use .html.erb as a file extension for my views with Sinatra?

一个人想着一个人 提交于 2019-12-04 02:09:36

Sinatra uses Tilt to render its templates, and to associate extensions with them. All you have to do is tell Tilt it should use ERB to render that extension:

Tilt.register Tilt::ERBTemplate, 'html.erb'

get '/hi' do
  erb :hello
end

Edit to answer follow-up question. There's no #unregister and also note that Sinatra will prefer hello.erb over hello.html.erb. The way around the preference issue is to either override the erb method or make your own render method:

Tilt.register Tilt::ERBTemplate, 'html.erb'

def herb(template, options={}, locals={})
  render "html.erb", template, options, locals
end

get '/hi' do
  herb :hello
end

That will prefer hello.html.erb, but will still fall back on hello.erb if it can't find hello.html.erb. If you really want to prevent .erb files from being found under any circumstances, you could, I guess, subclass ERBTemplate and register that against .html.erb instead, but frankly that just doesn't sound worth it.

This should do

get '/hi' do
  erb :'hello.html'
end

Or alternatively

get '/hi' do
  erb 'hello.html'.to_sym
end
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!