我有一个主要使用 erb 作为模板的 sinatra 应用程序,但我正在为需要在服务器端和客户端呈现的 html block 添加一些 mustache 部分。我有一个“views”目录,我在其中保存了所有模板,包括我添加的 mustache 模板。例如,结构看起来像这样:
views/
index.html.erb
_wingding.html.erb
_widget.html.mustache
假设我正在使用此端点呈现 index.html.erb:
get '/' do
erb :index
end
在该模板中,我想呈现上述两个部分 [更新:事实证明此 partial
方法并未内置到 sinatra 中,而是通过 gem 包含(请参阅我对细节的回答),但它仍然依赖于主要的 sinatra 渲染组件,所以这里的问题仍然存在。]。所以 index.html.erb 包含:
<%= partial :wingding %>
<%= partial :widget %>
erb 部分(wingding)渲染良好,但 mustache 部分(widget)没有。它会导致应用程序抛出异常:
Template engine not found: mustache
我在项目中包含了“ mustache ”gem。我尝试了 'require mustache/sinatra'
和 register Mustache::Sinatra
。这两种说法都有效,但没有解决上面的问题。知道如何告诉 sinatra 有关 mustache 的信息,以便它可以呈现 mustache 吗?
我通过包含此配置来设置我的 View 目录:
configure do
set :views, File.join(File.dirname(__FILE__), 'views')
end
版本号:
- 西纳特拉 1.3.1
- mustache 0.99.4
- ruby 1.9.3
最佳答案
所以结果是我的其他答案缓存输出中的解决方案中列出的 gem,这意味着您不能使用它在同一请求中包含具有不同本地的相同部分,这使得它对我的目的毫无值(value)。所以这是我已经确定的另一个(公认的 hackish)解决方案。我创建了一个助手,它只会传送给定 View 的内容:
helpers do
def template_contents(path)
File.open("#{settings.views}/#{path}") { |f| f.read }
end
end
然后,我只是做一个常规的 Mustache#render
:
<%= Mustache.render(template_contents('_widget.html.mustache'), { ... }) %>
这非常适合我的用例。
关于ruby - 如何在使用 ERB 作为主要模板引擎时在 Sinatra 中渲染 Mustache 部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13300085/