我想在Rails中将ERB模板呈现为纯文本。理想情况下,我可以做这样的事情:
应用程序/视图/测试/ test.txt.erb
Test
<%= @test %>
当我尝试时,Rails抱怨以下错误:
ActionView::MissingTemplate (Missing template test/test, application/test with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee]}. Searched in:
* "/Users/landonschropp/Development/test/app/views"
):
最简单的方法是采取行动:
render '/test/test.text.erb', layout: false, content_type: 'text/plain'
在我发现的方式是添加
Mime::Type.register 'text/plain', :txt
到environment.rb
如果需要,可以添加默认值:{format:'txt'}选项以路由定义
Rails.application.routes.draw do
root 'pages#home'
get 'test', to: 'pages#test', defaults: {format: 'txt'}
end
如果您只想渲染文件本身,请使用:
render "/test/test.text.erb"
在开头使用“/”非常重要,因为rails会识别它是一个文件。当然,它不会从html标签中逃脱“<”或“>”。
或者如果它的纯文本不完全来自文件,您可以内联它:
render plain: "OK"
只需使用......
render 'test', layout: false, formats: [:text]
...通常有效,假设你在test.text.erb
下的一个正常搜索位置有一个名为/app/views
的模板。
如果是简单的文字
render :text => "write your text here"