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

左心房为你撑大大i 提交于 2019-12-09 15:56:59

问题


If I have the following Sinatra code:

get '/hi' do
  erb :hello
end

This works great if I have a file called views/hello.erb. However if I have a file called views/hello.html.erb Sinatra can't find the file and gives me an error. How do I tell Sinatra I want it to look for .html.erb as a valid .erb extension?


回答1:


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.




回答2:


This should do

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

Or alternatively

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


来源:https://stackoverflow.com/questions/11741585/how-do-i-use-html-erb-as-a-file-extension-for-my-views-with-sinatra

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