簡體   English   中英

Rails純文本模板

[英]Rails plain text template

我想在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]

...通常有效,假設您在/app/views下的一個正常搜索位置中有一個名為test.text.erb的模板。

如果是簡單的文字

 render :text => "write your text here"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM