如何使用.html.erb作为Sinatra视图的文件扩展名? [英] How do I use .html.erb as a file extension for my views with Sinatra?

查看:88
本文介绍了如何使用.html.erb作为Sinatra视图的文件扩展名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有以下Sinatra代码:

If I have the following Sinatra code:

get '/hi' do
  erb :hello
end

如果我有一个名为 views / hello的文件,则效果很好.erb 。但是,如果我有一个名为 views / hello.html.erb 的文件,Sinatra无法找到该文件并给我一个错误。如何告诉Sinatra我希望它查找 .html.erb 作为有效的.erb扩展名?

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?

推荐答案

Sinatra使用倾斜呈现其模板并关联扩展跟他们。您所要做的就是告诉Tilt它应该使用ERB来呈现该扩展名:

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

编辑以回答后续问题。没有 #unregister ,并且请注意,Sinatra将更喜欢hello.erb,而不是hello.html.erb。解决首选项问题的方法是覆盖 erb 方法或制作自己的渲染方法:

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

这将更喜欢hello.html.erb,但是如果找不到hello.html.erb,它仍然会依赖hello.erb。如果您真的想防止在任何情况下都找到.erb文件,我可以将ERBTemplate子类化,然后将其注册到.html.erb中,但坦率地说,这听起来不值得

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.

这篇关于如何使用.html.erb作为Sinatra视图的文件扩展名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆