¿Cómo uso .html.erb como extensión de archivo para mis vistas con Sinatra?

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?

preguntado el 31 de julio de 12 a las 14:07

2 Respuestas

Usos de Sinatra inclinación 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

Editar 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 democracia 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.

Respondido 31 Jul 12, 20:07

Thank you! Works great, and also leaves .erb working too. Not that I'd want to mix conventions, but still handy to know. Do you know - if I didn't want to handle .erb any longer and just .html.erb, could I call something other than .register to disable .erb extensions? - mattmc3

Esto debería hacer

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

O alternativamente

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

Respondido 31 Jul 12, 17:07

+1. A reasonable alternative to Issac's answer, thank you. I want to set this convention globally rather than do this for every single route so I went with his answer. - mattmc3

That is a not a good suggestion given there is no ERB extension - kgpdesarrollador

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.