Rails Text Template Template

I would like to make the ERB template plain text in Rails. Ideally, I could do something like this:

app / views / test / test.txt.erb

Test <%= @test %> 

When I tried, Rails complained of the following error:

 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" ): 
+7
ruby-on-rails erb
source share
4 answers

The easiest way in your action:

 render '/test/test.text.erb', layout: false, content_type: 'text/plain' 
+8
source share

Ok, as I found, add this

 Mime::Type.register 'text/plain', :txt 

in environment.rb

If you need, you can add a default option: {format: 'txt'} to determine the route

 Rails.application.routes.draw do root 'pages#home' get 'test', to: 'pages#test', defaults: {format: 'txt'} end 
+2
source share

If you want to just make the file itself, use:

 render "/test/test.text.erb" 

It is important to use "/" at the beginning, as the rails recognize it as a file. Of course, he will not run away from "<" or ">" from html tags.

Or, if it is clearly not exactly from the file, you can embed it:

 render plain: "OK" 
0
source share

Just using ...

 render 'test', layout: false, formats: [:text] 

... usually works if you have a template called test.text.erb in one of the commonly found locations under /app/views .

0
source share

All Articles