-
Notifications
You must be signed in to change notification settings - Fork 0
/
layouts_and_rendering.html
1701 lines (1559 loc) · 89.2 KB
/
layouts_and_rendering.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Layouts and Rendering in Rails — Ruby on Rails Guides</title>
<link rel="stylesheet" type="text/css" href="stylesheets/style.css" data-turbolinks-track="reload">
<link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print">
<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shCore.css" data-turbolinks-track="reload">
<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shThemeRailsGuides.css" data-turbolinks-track="reload">
<link rel="stylesheet" type="text/css" href="stylesheets/fixes.css" data-turbolinks-track="reload">
<link href="images/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<script src="javascripts/syntaxhighlighter.js" data-turbolinks-track="reload"></script>
<script src="javascripts/turbolinks.js" data-turbolinks-track="reload"></script>
<script src="javascripts/guides.js" data-turbolinks-track="reload"></script>
<script src="javascripts/responsive-tables.js" data-turbolinks-track="reload"></script>
<meta property="og:title" content="Layouts and Rendering in Rails — Ruby on Rails Guides" />
<meta name="description" content="Layouts and Rendering in RailsThis guide covers the basic layout features of Action Controller and Action View.After reading this guide, you will know: How to use the various rendering methods built into Rails. How to create layouts with multiple content sections. How to use partials to DRY up your views. How to use nested layouts (sub-templates)." />
<meta property="og:description" content="Layouts and Rendering in RailsThis guide covers the basic layout features of Action Controller and Action View.After reading this guide, you will know: How to use the various rendering methods built into Rails. How to create layouts with multiple content sections. How to use partials to DRY up your views. How to use nested layouts (sub-templates)." />
<meta property="og:locale" content="en_US" />
<meta property="og:site_name" content="Ruby on Rails Guides" />
<meta property="og:image" content="https://avatars.githubusercontent.com/u/4223" />
<meta property="og:type" content="website" />
</head>
<body class="guide">
<div id="topNav">
<div class="wrapper">
<strong class="more-info-label">공식 웹사이트 <a href="https://rubyonrails.org/">rubyonrails.org:</a> </strong>
<span class="red-button more-info-button">
루비온레일스 웹사이트
</span>
<ul class="more-info-links s-hidden">
<li class="more-info"><a href="https://weblog.rubyonrails.org/">블로그</a></li>
<li class="more-info"><a href="https://guides.rubyonrails.org/">영문가이드</a></li>
<li class="more-info"><a href="https://api.rubyonrails.org/">레일스API</a></li>
<li class="more-info"><a href="https://stackoverflow.com/questions/tagged/ruby-on-rails">질문하기</a></li>
<li class="more-info"><a href="https://github.com/rails/rails">GitHub에서 기여하기</a></li>
</ul>
</div>
</div>
<div id="header">
<div class="wrapper clearfix">
<h1><a href="index.html" title="Return to home page">Guides.rubyonrails.org</a></h1>
<ul class="nav">
<li><a class="nav-item" href="index.html">홈</a></li>
<li class="guides-index guides-index-large">
<a href="index.html" id="guidesMenu" class="guides-index-item nav-item">가이드 인덱스</a>
<div id="guides" class="clearfix" style="display: none;">
<hr />
<div class="guides-section-container">
<div class="guides-section">
<dt>시작하면서</dt>
<dd><a href="getting_started.html">레일스로 시작하기</a></dd>
</div>
<div class="guides-section">
<dt>모델</dt>
<dd><a href="active_record_basics.html">액티브 레코드 기본</a></dd>
<dd><a href="active_record_migrations.html">액티브 레코드 마이그레이션</a></dd>
<dd><a href="active_record_validations.html">액티브 레코드 유효성 검증</a></dd>
<dd><a href="active_record_callbacks.html">액티브 레코드 콜백</a></dd>
<dd><a href="association_basics.html">Active Record Associations</a></dd>
<dd><a href="active_record_querying.html">Active Record Query Interface</a></dd>
</div>
<div class="guides-section">
<dt>Views</dt>
<dd><a href="layouts_and_rendering.html">Layouts and Rendering in Rails</a></dd>
<dd><a href="form_helpers.html">Action View Form Helpers</a></dd>
</div>
<div class="guides-section">
<dt>Controllers</dt>
<dd><a href="action_controller_overview.html">Action Controller Overview</a></dd>
<dd><a href="routing.html">Rails Routing from the Outside In</a></dd>
</div>
<div class="guides-section">
<dt>Other Components</dt>
<dd><a href="active_support_core_extensions.html">Active Support Core Extensions</a></dd>
<dd><a href="action_mailer_basics.html">Action Mailer Basics</a></dd>
<dd><a href="active_job_basics.html">Active Job Basics</a></dd>
<dd><a href="active_storage_overview.html">Active Storage Overview</a></dd>
<dd><a href="action_cable_overview.html">Action Cable Overview</a></dd>
</div>
<div class="guides-section">
<dt>Digging Deeper</dt>
<dd><a href="i18n.html">Rails Internationalization (I18n) API</a></dd>
<dd><a href="testing.html">Testing Rails Applications</a></dd>
<dd><a href="security.html">Securing Rails Applications</a></dd>
<dd><a href="debugging_rails_applications.html">Debugging Rails Applications</a></dd>
<dd><a href="configuring.html">Configuring Rails Applications</a></dd>
<dd><a href="command_line.html">The Rails Command Line</a></dd>
<dd><a href="asset_pipeline.html">The Asset Pipeline</a></dd>
<dd><a href="working_with_javascript_in_rails.html">Working with JavaScript in Rails</a></dd>
<dd><a href="autoloading_and_reloading_constants.html">Autoloading and Reloading Constants (Zeitwerk Mode)</a></dd>
<dd><a href="autoloading_and_reloading_constants_classic_mode.html">Autoloading and Reloading Constants (Classic Mode)</a></dd>
<dd><a href="caching_with_rails.html">Caching with Rails: An Overview</a></dd>
<dd><a href="api_app.html">Using Rails for API-only Applications</a></dd>
</div>
<div class="guides-section">
<dt>Extending Rails</dt>
<dd><a href="rails_on_rack.html">Rails on Rack</a></dd>
<dd><a href="generators.html">Creating and Customizing Rails Generators & Templates</a></dd>
</div>
<div class="guides-section">
<dt>Contributions</dt>
<dd><a href="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</a></dd>
<dd><a href="api_documentation_guidelines.html">API Documentation Guidelines</a></dd>
<dd><a href="ruby_on_rails_guides_guidelines.html">Guides Guidelines</a></dd>
</div>
<div class="guides-section">
<dt>Policies</dt>
<dd><a href="maintenance_policy.html">Maintenance Policy</a></dd>
</div>
<div class="guides-section">
<dt>Release Notes</dt>
<dd><a href="upgrading_ruby_on_rails.html">Upgrading Ruby on Rails</a></dd>
<dd><a href="6_0_release_notes.html">Version 6.0 - August 2019</a></dd>
<dd><a href="5_2_release_notes.html">Version 5.2 - April 2018</a></dd>
<dd><a href="5_1_release_notes.html">Version 5.1 - April 2017</a></dd>
<dd><a href="5_0_release_notes.html">Version 5.0 - June 2016</a></dd>
<dd><a href="4_2_release_notes.html">Version 4.2 - December 2014</a></dd>
<dd><a href="4_1_release_notes.html">Version 4.1 - April 2014</a></dd>
<dd><a href="4_0_release_notes.html">Version 4.0 - June 2013</a></dd>
<dd><a href="3_2_release_notes.html">Version 3.2 - January 2012</a></dd>
<dd><a href="3_1_release_notes.html">Version 3.1 - August 2011</a></dd>
<dd><a href="3_0_release_notes.html">Version 3.0 - August 2010</a></dd>
<dd><a href="2_3_release_notes.html">Version 2.3 - March 2009</a></dd>
<dd><a href="2_2_release_notes.html">Version 2.2 - November 2008</a></dd>
</div>
</div>
</div>
</li>
<li><a class="nav-item" href="contributing_to_ruby_on_rails.html">기여하기</a></li>
<li class="guides-index guides-index-small">
<select class="guides-index-item nav-item">
<option value="index.html">가이드 인덱스</option>
<optgroup label="시작하면서">
<option value="getting_started.html">레일스로 시작하기</option>
</optgroup>
<optgroup label="모델">
<option value="active_record_basics.html">액티브 레코드 기본</option>
<option value="active_record_migrations.html">액티브 레코드 마이그레이션</option>
<option value="active_record_validations.html">액티브 레코드 유효성 검증</option>
<option value="active_record_callbacks.html">액티브 레코드 콜백</option>
<option value="association_basics.html">Active Record Associations</option>
<option value="active_record_querying.html">Active Record Query Interface</option>
</optgroup>
<optgroup label="Views">
<option value="layouts_and_rendering.html">Layouts and Rendering in Rails</option>
<option value="form_helpers.html">Action View Form Helpers</option>
</optgroup>
<optgroup label="Controllers">
<option value="action_controller_overview.html">Action Controller Overview</option>
<option value="routing.html">Rails Routing from the Outside In</option>
</optgroup>
<optgroup label="Other Components">
<option value="active_support_core_extensions.html">Active Support Core Extensions</option>
<option value="action_mailer_basics.html">Action Mailer Basics</option>
<option value="active_job_basics.html">Active Job Basics</option>
<option value="active_storage_overview.html">Active Storage Overview</option>
<option value="action_cable_overview.html">Action Cable Overview</option>
</optgroup>
<optgroup label="Digging Deeper">
<option value="i18n.html">Rails Internationalization (I18n) API</option>
<option value="testing.html">Testing Rails Applications</option>
<option value="security.html">Securing Rails Applications</option>
<option value="debugging_rails_applications.html">Debugging Rails Applications</option>
<option value="configuring.html">Configuring Rails Applications</option>
<option value="command_line.html">The Rails Command Line</option>
<option value="asset_pipeline.html">The Asset Pipeline</option>
<option value="working_with_javascript_in_rails.html">Working with JavaScript in Rails</option>
<option value="autoloading_and_reloading_constants.html">Autoloading and Reloading Constants (Zeitwerk Mode)</option>
<option value="autoloading_and_reloading_constants_classic_mode.html">Autoloading and Reloading Constants (Classic Mode)</option>
<option value="caching_with_rails.html">Caching with Rails: An Overview</option>
<option value="api_app.html">Using Rails for API-only Applications</option>
</optgroup>
<optgroup label="Extending Rails">
<option value="rails_on_rack.html">Rails on Rack</option>
<option value="generators.html">Creating and Customizing Rails Generators & Templates</option>
</optgroup>
<optgroup label="Contributions">
<option value="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</option>
<option value="api_documentation_guidelines.html">API Documentation Guidelines</option>
<option value="ruby_on_rails_guides_guidelines.html">Guides Guidelines</option>
</optgroup>
<optgroup label="Policies">
<option value="maintenance_policy.html">Maintenance Policy</option>
</optgroup>
<optgroup label="Release Notes">
<option value="upgrading_ruby_on_rails.html">Upgrading Ruby on Rails</option>
<option value="6_0_release_notes.html">Version 6.0 - August 2019</option>
<option value="5_2_release_notes.html">Version 5.2 - April 2018</option>
<option value="5_1_release_notes.html">Version 5.1 - April 2017</option>
<option value="5_0_release_notes.html">Version 5.0 - June 2016</option>
<option value="4_2_release_notes.html">Version 4.2 - December 2014</option>
<option value="4_1_release_notes.html">Version 4.1 - April 2014</option>
<option value="4_0_release_notes.html">Version 4.0 - June 2013</option>
<option value="3_2_release_notes.html">Version 3.2 - January 2012</option>
<option value="3_1_release_notes.html">Version 3.1 - August 2011</option>
<option value="3_0_release_notes.html">Version 3.0 - August 2010</option>
<option value="2_3_release_notes.html">Version 2.3 - March 2009</option>
<option value="2_2_release_notes.html">Version 2.2 - November 2008</option>
</optgroup>
</select>
</li>
</ul>
</div>
</div>
<hr class="hide" />
<div id="feature">
<div class="wrapper">
<h2>Layouts and Rendering in Rails</h2><p>This guide covers the basic layout features of Action Controller and Action View.</p><p>After reading this guide, you will know:</p>
<ul>
<li>How to use the various rendering methods built into Rails.</li>
<li>How to create layouts with multiple content sections.</li>
<li>How to use partials to DRY up your views.</li>
<li>How to use nested layouts (sub-templates).</li>
</ul>
<div id="subCol">
<h3 class="chapter"><img src="images/chapters_icon.gif" alt="" />Chapters</h3>
<ol class="chapters">
<li><a href="#overview-how-the-pieces-fit-together">Overview: How the Pieces Fit Together</a></li>
<li>
<a href="#creating-responses">Creating Responses</a>
<ul>
<li><a href="#rendering-by-default-convention-over-configuration-in-action">Rendering by Default: Convention Over Configuration in Action</a></li>
<li><a href="#using-render">Using <code>render</code></a></li>
<li><a href="#using-redirect-to">Using <code>redirect_to</code></a></li>
<li><a href="#using-head-to-build-header-only-responses">Using <code>head</code> To Build Header-Only Responses</a></li>
</ul>
</li>
<li>
<a href="#structuring-layouts">Structuring Layouts</a>
<ul>
<li><a href="#asset-tag-helpers">Asset Tag Helpers</a></li>
<li><a href="#understanding-yield">Understanding <code>yield</code></a></li>
<li><a href="#using-the-content-for-method">Using the <code>content_for</code> Method</a></li>
<li><a href="#using-partials">Using Partials</a></li>
<li><a href="#using-nested-layouts">Using Nested Layouts</a></li>
</ul>
</li>
</ol>
</div>
</div>
</div>
<div id="container">
<div class="wrapper">
<div id="mainCol">
<h3 id="overview-how-the-pieces-fit-together"><a class="anchorlink" href="#overview-how-the-pieces-fit-together">1 Overview: How the Pieces Fit Together</a></h3><p>This guide focuses on the interaction between Controller and View in the Model-View-Controller triangle. As you know, the Controller is responsible for orchestrating the whole process of handling a request in Rails, though it normally hands off any heavy code to the Model. But then, when it's time to send a response back to the user, the Controller hands things off to the View. It's that handoff that is the subject of this guide.</p><p>In broad strokes, this involves deciding what should be sent as the response and calling an appropriate method to create that response. If the response is a full-blown view, Rails also does some extra work to wrap the view in a layout and possibly to pull in partial views. You'll see all of those paths later in this guide.</p><h3 id="creating-responses"><a class="anchorlink" href="#creating-responses">2 Creating Responses</a></h3><p>From the controller's point of view, there are three ways to create an HTTP response:</p>
<ul>
<li>Call <code>render</code> to create a full response to send back to the browser</li>
<li>Call <code>redirect_to</code> to send an HTTP redirect status code to the browser</li>
<li>Call <code>head</code> to create a response consisting solely of HTTP headers to send back to the browser</li>
</ul>
<h4 id="rendering-by-default-convention-over-configuration-in-action"><a class="anchorlink" href="#rendering-by-default-convention-over-configuration-in-action">2.1 Rendering by Default: Convention Over Configuration in Action</a></h4><p>You've heard that Rails promotes "convention over configuration". Default rendering is an excellent example of this. By default, controllers in Rails automatically render views with names that correspond to valid routes. For example, if you have this code in your <code>BooksController</code> class:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class BooksController < ApplicationController
end
</pre>
</div>
<p>And the following in your routes file:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
resources :books
</pre>
</div>
<p>And you have a view file <code>app/views/books/index.html.erb</code>:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<h1>Books are coming soon!</h1>
</pre>
</div>
<p>Rails will automatically render <code>app/views/books/index.html.erb</code> when you navigate to <code>/books</code> and you will see "Books are coming soon!" on your screen.</p><p>However a coming soon screen is only minimally useful, so you will soon create your <code>Book</code> model and add the index action to <code>BooksController</code>:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class BooksController < ApplicationController
def index
@books = Book.all
end
end
</pre>
</div>
<p>Note that we don't have explicit render at the end of the index action in accordance with "convention over configuration" principle. The rule is that if you do not explicitly render something at the end of a controller action, Rails will automatically look for the <code>action_name.html.erb</code> template in the controller's view path and render it. So in this case, Rails will render the <code>app/views/books/index.html.erb</code> file.</p><p>If we want to display the properties of all the books in our view, we can do so with an ERB template like this:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<h1>Listing Books</h1>
<table>
<thead>
<tr>
<th>Title</th>
<th>Content</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% @books.each do |book| %>
<tr>
<td><%= book.title %></td>
<td><%= book.content %></td>
<td><%= link_to "Show", book %></td>
<td><%= link_to "Edit", edit_book_path(book) %></td>
<td><%= link_to "Destroy", book, method: :delete, data: { confirm: "Are you sure?" } %></td>
</tr>
<% end %>
</tbody>
</table>
<br>
<%= link_to "New book", new_book_path %>
</pre>
</div>
<div class="note"><p>The actual rendering is done by nested classes of the module <a href="https://api.rubyonrails.org/6-0-stable/classes/ActionView/Template/Handlers.html"><code>ActionView::Template::Handlers</code></a>. This guide does not dig into that process, but it's important to know that the file extension on your view controls the choice of template handler.</p></div><h4 id="using-render"><a class="anchorlink" href="#using-render">2.2 Using <code>render</code></a></h4><p>In most cases, the <code>ActionController::Base#render</code> method does the heavy lifting of rendering your application's content for use by a browser. There are a variety of ways to customize the behavior of <code>render</code>. You can render the default view for a Rails template, or a specific template, or a file, or inline code, or nothing at all. You can render text, JSON, or XML. You can specify the content type or HTTP status of the rendered response as well.</p><div class="info"><p>If you want to see the exact results of a call to <code>render</code> without needing to inspect it in a browser, you can call <code>render_to_string</code>. This method takes exactly the same options as <code>render</code>, but it returns a string instead of sending a response back to the browser.</p></div><h5 id="rendering-an-action-s-view"><a class="anchorlink" href="#rendering-an-action-s-view">2.2.1 Rendering an Action's View</a></h5><p>If you want to render the view that corresponds to a different template within the same controller, you can use <code>render</code> with the name of the view:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
def update
@book = Book.find(params[:id])
if @book.update(book_params)
redirect_to(@book)
else
render "edit"
end
end
</pre>
</div>
<p>If the call to <code>update</code> fails, calling the <code>update</code> action in this controller will render the <code>edit.html.erb</code> template belonging to the same controller.</p><p>If you prefer, you can use a symbol instead of a string to specify the action to render:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
def update
@book = Book.find(params[:id])
if @book.update(book_params)
redirect_to(@book)
else
render :edit
end
end
</pre>
</div>
<h5 id="rendering-an-action-s-template-from-another-controller"><a class="anchorlink" href="#rendering-an-action-s-template-from-another-controller">2.2.2 Rendering an Action's Template from Another Controller</a></h5><p>What if you want to render a template from an entirely different controller from the one that contains the action code? You can also do that with <code>render</code>, which accepts the full path (relative to <code>app/views</code>) of the template to render. For example, if you're running code in an <code>AdminProductsController</code> that lives in <code>app/controllers/admin</code>, you can render the results of an action to a template in <code>app/views/products</code> this way:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
render "products/show"
</pre>
</div>
<p>Rails knows that this view belongs to a different controller because of the embedded slash character in the string. If you want to be explicit, you can use the <code>:template</code> option (which was required on Rails 2.2 and earlier):</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
render template: "products/show"
</pre>
</div>
<h5 id="wrapping-it-up"><a class="anchorlink" href="#wrapping-it-up">2.2.3 Wrapping it up</a></h5><p>The above three ways of rendering (rendering another template within the controller, rendering a template within another controller, and rendering an arbitrary file on the file system) are actually variants of the same action.</p><p>In fact, in the BooksController class, inside of the update action where we want to render the edit template if the book does not update successfully, all of the following render calls would all render the <code>edit.html.erb</code> template in the <code>views/books</code> directory:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
render :edit
render action: :edit
render "edit"
render action: "edit"
render "books/edit"
render template: "books/edit"
</pre>
</div>
<p>Which one you use is really a matter of style and convention, but the rule of thumb is to use the simplest one that makes sense for the code you are writing.</p><h5 id="using-render-with-inline"><a class="anchorlink" href="#using-render-with-inline">2.2.4 Using <code>render</code> with <code>:inline</code></a></h5><p>The <code>render</code> method can do without a view completely, if you're willing to use the <code>:inline</code> option to supply ERB as part of the method call. This is perfectly valid:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
render inline: "<% products.each do |p| %><p><%= p.name %></p><% end %>"
</pre>
</div>
<div class="warning"><p>There is seldom any good reason to use this option. Mixing ERB into your controllers defeats the MVC orientation of Rails and will make it harder for other developers to follow the logic of your project. Use a separate erb view instead.</p></div><p>By default, inline rendering uses ERB. You can force it to use Builder instead with the <code>:type</code> option:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
render inline: "xml.p {'Horrid coding practice!'}", type: :builder
</pre>
</div>
<h5 id="rendering-text"><a class="anchorlink" href="#rendering-text">2.2.5 Rendering Text</a></h5><p>You can send plain text - with no markup at all - back to the browser by using
the <code>:plain</code> option to <code>render</code>:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
render plain: "OK"
</pre>
</div>
<div class="info"><p>Rendering pure text is most useful when you're responding to Ajax or web
service requests that are expecting something other than proper HTML.</p></div><div class="note"><p>By default, if you use the <code>:plain</code> option, the text is rendered without
using the current layout. If you want Rails to put the text into the current
layout, you need to add the <code>layout: true</code> option and use the <code>.text.erb</code>
extension for the layout file.</p></div><h5 id="rendering-html"><a class="anchorlink" href="#rendering-html">2.2.6 Rendering HTML</a></h5><p>You can send an HTML string back to the browser by using the <code>:html</code> option to
<code>render</code>:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
render html: helpers.tag.strong('Not Found')
</pre>
</div>
<div class="info"><p>This is useful when you're rendering a small snippet of HTML code.
However, you might want to consider moving it to a template file if the markup
is complex.</p></div><div class="note"><p>When using <code>html:</code> option, HTML entities will be escaped if the string is not composed with <code>html_safe</code>-aware APIs.</p></div><h5 id="rendering-json"><a class="anchorlink" href="#rendering-json">2.2.7 Rendering JSON</a></h5><p>JSON is a JavaScript data format used by many Ajax libraries. Rails has built-in support for converting objects to JSON and rendering that JSON back to the browser:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
render json: @product
</pre>
</div>
<div class="info"><p>You don't need to call <code>to_json</code> on the object that you want to render. If you use the <code>:json</code> option, <code>render</code> will automatically call <code>to_json</code> for you.</p></div><h5 id="rendering-xml"><a class="anchorlink" href="#rendering-xml">2.2.8 Rendering XML</a></h5><p>Rails also has built-in support for converting objects to XML and rendering that XML back to the caller:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
render xml: @product
</pre>
</div>
<div class="info"><p>You don't need to call <code>to_xml</code> on the object that you want to render. If you use the <code>:xml</code> option, <code>render</code> will automatically call <code>to_xml</code> for you.</p></div><h5 id="rendering-vanilla-javascript"><a class="anchorlink" href="#rendering-vanilla-javascript">2.2.9 Rendering Vanilla JavaScript</a></h5><p>Rails can render vanilla JavaScript:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
render js: "alert('Hello Rails');"
</pre>
</div>
<p>This will send the supplied string to the browser with a MIME type of <code>text/javascript</code>.</p><h5 id="rendering-raw-body"><a class="anchorlink" href="#rendering-raw-body">2.2.10 Rendering raw body</a></h5><p>You can send a raw content back to the browser, without setting any content
type, by using the <code>:body</code> option to <code>render</code>:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
render body: "raw"
</pre>
</div>
<div class="info"><p>This option should be used only if you don't care about the content type of
the response. Using <code>:plain</code> or <code>:html</code> might be more appropriate most of the
time.</p></div><div class="note"><p>Unless overridden, your response returned from this render option will be
<code>text/plain</code>, as that is the default content type of Action Dispatch response.</p></div><h5 id="rendering-raw-file"><a class="anchorlink" href="#rendering-raw-file">2.2.11 Rendering raw file</a></h5><p>Rails can render a raw file from an absolute path. This is useful for
conditionally rendering static files like error pages.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
render file: "#{Rails.root}/public/404.html", layout: false
</pre>
</div>
<p>This renders the raw file (it doesn't support ERB or other handlers). By
default it is rendered within the current layout.</p><div class="warning"><p>Using the <code>:file</code> option in combination with users input can lead to security problems
since an attacker could use this action to access security sensitive files in your file system.</p></div><div class="info"><p><code>send_file</code> is often a faster and better option if a layout isn't required.</p></div><h5 id="options-for-render"><a class="anchorlink" href="#options-for-render">2.2.12 Options for <code>render</code></a></h5><p>Calls to the <code>render</code> method generally accept five options:</p>
<ul>
<li><code>:content_type</code></li>
<li><code>:layout</code></li>
<li><code>:location</code></li>
<li><code>:status</code></li>
<li><code>:formats</code></li>
<li><code>:variants</code></li>
</ul>
<h6 id="the-content-type-option"><a class="anchorlink" href="#the-content-type-option">2.2.12.1 The <code>:content_type</code> Option</a></h6><p>By default, Rails will serve the results of a rendering operation with the MIME content-type of <code>text/html</code> (or <code>application/json</code> if you use the <code>:json</code> option, or <code>application/xml</code> for the <code>:xml</code> option.). There are times when you might like to change this, and you can do so by setting the <code>:content_type</code> option:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
render template: "feed", content_type: "application/rss"
</pre>
</div>
<h6 id="the-layout-option"><a class="anchorlink" href="#the-layout-option">2.2.12.2 The <code>:layout</code> Option</a></h6><p>With most of the options to <code>render</code>, the rendered content is displayed as part of the current layout. You'll learn more about layouts and how to use them later in this guide.</p><p>You can use the <code>:layout</code> option to tell Rails to use a specific file as the layout for the current action:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
render layout: "special_layout"
</pre>
</div>
<p>You can also tell Rails to render with no layout at all:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
render layout: false
</pre>
</div>
<h6 id="the-location-option"><a class="anchorlink" href="#the-location-option">2.2.12.3 The <code>:location</code> Option</a></h6><p>You can use the <code>:location</code> option to set the HTTP <code>Location</code> header:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
render xml: photo, location: photo_url(photo)
</pre>
</div>
<h6 id="the-status-option"><a class="anchorlink" href="#the-status-option">2.2.12.4 The <code>:status</code> Option</a></h6><p>Rails will automatically generate a response with the correct HTTP status code (in most cases, this is <code>200 OK</code>). You can use the <code>:status</code> option to change this:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
render status: 500
render status: :forbidden
</pre>
</div>
<p>Rails understands both numeric status codes and the corresponding symbols shown below.</p>
<table>
<thead>
<tr>
<th>Response Class</th>
<th>HTTP Status Code</th>
<th>Symbol</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Informational</strong></td>
<td>100</td>
<td>:continue</td>
</tr>
<tr>
<td></td>
<td>101</td>
<td>:switching_protocols</td>
</tr>
<tr>
<td></td>
<td>102</td>
<td>:processing</td>
</tr>
<tr>
<td><strong>Success</strong></td>
<td>200</td>
<td>:ok</td>
</tr>
<tr>
<td></td>
<td>201</td>
<td>:created</td>
</tr>
<tr>
<td></td>
<td>202</td>
<td>:accepted</td>
</tr>
<tr>
<td></td>
<td>203</td>
<td>:non_authoritative_information</td>
</tr>
<tr>
<td></td>
<td>204</td>
<td>:no_content</td>
</tr>
<tr>
<td></td>
<td>205</td>
<td>:reset_content</td>
</tr>
<tr>
<td></td>
<td>206</td>
<td>:partial_content</td>
</tr>
<tr>
<td></td>
<td>207</td>
<td>:multi_status</td>
</tr>
<tr>
<td></td>
<td>208</td>
<td>:already_reported</td>
</tr>
<tr>
<td></td>
<td>226</td>
<td>:im_used</td>
</tr>
<tr>
<td><strong>Redirection</strong></td>
<td>300</td>
<td>:multiple_choices</td>
</tr>
<tr>
<td></td>
<td>301</td>
<td>:moved_permanently</td>
</tr>
<tr>
<td></td>
<td>302</td>
<td>:found</td>
</tr>
<tr>
<td></td>
<td>303</td>
<td>:see_other</td>
</tr>
<tr>
<td></td>
<td>304</td>
<td>:not_modified</td>
</tr>
<tr>
<td></td>
<td>305</td>
<td>:use_proxy</td>
</tr>
<tr>
<td></td>
<td>307</td>
<td>:temporary_redirect</td>
</tr>
<tr>
<td></td>
<td>308</td>
<td>:permanent_redirect</td>
</tr>
<tr>
<td><strong>Client Error</strong></td>
<td>400</td>
<td>:bad_request</td>
</tr>
<tr>
<td></td>
<td>401</td>
<td>:unauthorized</td>
</tr>
<tr>
<td></td>
<td>402</td>
<td>:payment_required</td>
</tr>
<tr>
<td></td>
<td>403</td>
<td>:forbidden</td>
</tr>
<tr>
<td></td>
<td>404</td>
<td>:not_found</td>
</tr>
<tr>
<td></td>
<td>405</td>
<td>:method_not_allowed</td>
</tr>
<tr>
<td></td>
<td>406</td>
<td>:not_acceptable</td>
</tr>
<tr>
<td></td>
<td>407</td>
<td>:proxy_authentication_required</td>
</tr>
<tr>
<td></td>
<td>408</td>
<td>:request_timeout</td>
</tr>
<tr>
<td></td>
<td>409</td>
<td>:conflict</td>
</tr>
<tr>
<td></td>
<td>410</td>
<td>:gone</td>
</tr>
<tr>
<td></td>
<td>411</td>
<td>:length_required</td>
</tr>
<tr>
<td></td>
<td>412</td>
<td>:precondition_failed</td>
</tr>
<tr>
<td></td>
<td>413</td>
<td>:payload_too_large</td>
</tr>
<tr>
<td></td>
<td>414</td>
<td>:uri_too_long</td>
</tr>
<tr>
<td></td>
<td>415</td>
<td>:unsupported_media_type</td>
</tr>
<tr>
<td></td>
<td>416</td>
<td>:range_not_satisfiable</td>
</tr>
<tr>
<td></td>
<td>417</td>
<td>:expectation_failed</td>
</tr>
<tr>
<td></td>
<td>421</td>
<td>:misdirected_request</td>
</tr>
<tr>
<td></td>
<td>422</td>
<td>:unprocessable_entity</td>
</tr>
<tr>
<td></td>
<td>423</td>
<td>:locked</td>
</tr>
<tr>
<td></td>
<td>424</td>
<td>:failed_dependency</td>
</tr>
<tr>
<td></td>
<td>426</td>
<td>:upgrade_required</td>
</tr>
<tr>
<td></td>
<td>428</td>
<td>:precondition_required</td>
</tr>
<tr>
<td></td>
<td>429</td>
<td>:too_many_requests</td>
</tr>
<tr>
<td></td>
<td>431</td>
<td>:request_header_fields_too_large</td>
</tr>
<tr>
<td></td>
<td>451</td>
<td>:unavailable_for_legal_reasons</td>
</tr>
<tr>
<td><strong>Server Error</strong></td>
<td>500</td>
<td>:internal_server_error</td>
</tr>
<tr>
<td></td>
<td>501</td>
<td>:not_implemented</td>
</tr>
<tr>
<td></td>
<td>502</td>
<td>:bad_gateway</td>
</tr>
<tr>
<td></td>
<td>503</td>
<td>:service_unavailable</td>
</tr>
<tr>
<td></td>
<td>504</td>
<td>:gateway_timeout</td>
</tr>
<tr>
<td></td>
<td>505</td>
<td>:http_version_not_supported</td>
</tr>
<tr>
<td></td>
<td>506</td>
<td>:variant_also_negotiates</td>
</tr>
<tr>
<td></td>
<td>507</td>
<td>:insufficient_storage</td>
</tr>
<tr>
<td></td>
<td>508</td>
<td>:loop_detected</td>
</tr>
<tr>
<td></td>
<td>510</td>
<td>:not_extended</td>
</tr>
<tr>
<td></td>
<td>511</td>
<td>:network_authentication_required</td>
</tr>
</tbody>
</table>
<div class="note"><p>If you try to render content along with a non-content status code
(100-199, 204, 205, or 304), it will be dropped from the response.</p></div><h6 id="the-formats-option"><a class="anchorlink" href="#the-formats-option">2.2.12.5 The <code>:formats</code> Option</a></h6><p>Rails uses the format specified in the request (or <code>:html</code> by default). You can
change this passing the <code>:formats</code> option with a symbol or an array:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
render formats: :xml
render formats: [:json, :xml]
</pre>
</div>
<p>If a template with the specified format does not exist an <code>ActionView::MissingTemplate</code> error is raised.</p><h6 id="the-variants-option"><a class="anchorlink" href="#the-variants-option">2.2.12.6 The <code>:variants</code> Option</a></h6><p>This tells Rails to look for template variations of the same format.
You can specify a list of variants by passing the <code>:variants</code> option with a symbol or an array. </p><p>An example of use would be this.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# called in HomeController#index
render variants: [:mobile, :desktop]
</pre>
</div>
<p>With this set of variants Rails will look for the following set of templates and use the first that exists.</p>
<ul>
<li><code>app/views/home/index.html+mobile.erb</code></li>
<li><code>app/views/home/index.html+desktop.erb</code></li>
<li><code>app/views/home/index.html.erb</code></li>
</ul>
<p>If a template with the specified format does not exist an <code>ActionView::MissingTemplate</code> error is raised.</p><p>Instead of setting the variant on the render call you may also set it on the request object in your controller action.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
def index
request.variant = determine_variant
end
private
def determine_variant
variant = nil
# some code to determine the variant(s) to use
variant = :mobile if session[:use_mobile]
variant
end
</pre>
</div>
<h5 id="finding-layouts"><a class="anchorlink" href="#finding-layouts">2.2.13 Finding Layouts</a></h5><p>To find the current layout, Rails first looks for a file in <code>app/views/layouts</code> with the same base name as the controller. For example, rendering actions from the <code>PhotosController</code> class will use <code>app/views/layouts/photos.html.erb</code> (or <code>app/views/layouts/photos.builder</code>). If there is no such controller-specific layout, Rails will use <code>app/views/layouts/application.html.erb</code> or <code>app/views/layouts/application.builder</code>. If there is no <code>.erb</code> layout, Rails will use a <code>.builder</code> layout if one exists. Rails also provides several ways to more precisely assign specific layouts to individual controllers and actions.</p><h6 id="specifying-layouts-for-controllers"><a class="anchorlink" href="#specifying-layouts-for-controllers">2.2.13.1 Specifying Layouts for Controllers</a></h6><p>You can override the default layout conventions in your controllers by using the <code>layout</code> declaration. For example:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class ProductsController < ApplicationController
layout "inventory"
#...
end
</pre>
</div>
<p>With this declaration, all of the views rendered by the <code>ProductsController</code> will use <code>app/views/layouts/inventory.html.erb</code> as their layout.</p><p>To assign a specific layout for the entire application, use a <code>layout</code> declaration in your <code>ApplicationController</code> class:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class ApplicationController < ActionController::Base
layout "main"
#...
end
</pre>
</div>
<p>With this declaration, all of the views in the entire application will use <code>app/views/layouts/main.html.erb</code> for their layout.</p><h6 id="choosing-layouts-at-runtime"><a class="anchorlink" href="#choosing-layouts-at-runtime">2.2.13.2 Choosing Layouts at Runtime</a></h6><p>You can use a symbol to defer the choice of layout until a request is processed:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class ProductsController < ApplicationController
layout :products_layout
def show
@product = Product.find(params[:id])
end
private
def products_layout
@current_user.special? ? "special" : "products"
end
end
</pre>
</div>
<p>Now, if the current user is a special user, they'll get a special layout when viewing a product.</p><p>You can even use an inline method, such as a Proc, to determine the layout. For example, if you pass a Proc object, the block you give the Proc will be given the <code>controller</code> instance, so the layout can be determined based on the current request:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class ProductsController < ApplicationController
layout Proc.new { |controller| controller.request.xhr? ? "popup" : "application" }
end
</pre>
</div>
<h6 id="conditional-layouts"><a class="anchorlink" href="#conditional-layouts">2.2.13.3 Conditional Layouts</a></h6><p>Layouts specified at the controller level support the <code>:only</code> and <code>:except</code> options. These options take either a method name, or an array of method names, corresponding to method names within the controller:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class ProductsController < ApplicationController
layout "product", except: [:index, :rss]
end
</pre>
</div>
<p>With this declaration, the <code>product</code> layout would be used for everything but the <code>rss</code> and <code>index</code> methods.</p><h6 id="layout-inheritance"><a class="anchorlink" href="#layout-inheritance">2.2.13.4 Layout Inheritance</a></h6><p>Layout declarations cascade downward in the hierarchy, and more specific layout declarations always override more general ones. For example:</p>
<ul>
<li>
<p><code>application_controller.rb</code></p>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class ApplicationController < ActionController::Base
layout "main"
end
</pre>
</div>
</li>
<li>
<p><code>articles_controller.rb</code></p>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class ArticlesController < ApplicationController
end
</pre>
</div>
</li>
<li>
<p><code>special_articles_controller.rb</code></p>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class SpecialArticlesController < ArticlesController
layout "special"
end
</pre>
</div>
</li>
<li>
<p><code>old_articles_controller.rb</code></p>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class OldArticlesController < SpecialArticlesController
layout false
def show
@article = Article.find(params[:id])
end
def index
@old_articles = Article.older
render layout: "old"
end
# ...
end
</pre>
</div>
</li>
</ul>
<p>In this application:</p>
<ul>
<li>In general, views will be rendered in the <code>main</code> layout</li>
<li>
<code>ArticlesController#index</code> will use the <code>main</code> layout</li>
<li>
<code>SpecialArticlesController#index</code> will use the <code>special</code> layout</li>
<li>
<code>OldArticlesController#show</code> will use no layout at all</li>
<li>
<code>OldArticlesController#index</code> will use the <code>old</code> layout</li>
</ul>
<h6 id="template-inheritance"><a class="anchorlink" href="#template-inheritance">2.2.13.5 Template Inheritance</a></h6><p>Similar to the Layout Inheritance logic, if a template or partial is not found in the conventional path, the controller will look for a template or partial to render in its inheritance chain. For example:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# in app/controllers/application_controller
class ApplicationController < ActionController::Base
end
# in app/controllers/admin_controller
class AdminController < ApplicationController
end
# in app/controllers/admin/products_controller
class Admin::ProductsController < AdminController
def index
end
end
</pre>
</div>
<p>The lookup order for an <code>admin/products#index</code> action will be:</p>
<ul>
<li><code>app/views/admin/products/</code></li>
<li><code>app/views/admin/</code></li>
<li><code>app/views/application/</code></li>
</ul>
<p>This makes <code>app/views/application/</code> a great place for your shared partials, which can then be rendered in your ERB as such:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%# app/views/admin/products/index.html.erb %>
<%= render @products || "empty_list" %>
<%# app/views/application/_empty_list.html.erb %>
There are no items in this list <em>yet</em>.
</pre>
</div>
<h5 id="avoiding-double-render-errors"><a class="anchorlink" href="#avoiding-double-render-errors">2.2.14 Avoiding Double Render Errors</a></h5><p>Sooner or later, most Rails developers will see the error message "Can only render or redirect once per action". While this is annoying, it's relatively easy to fix. Usually it happens because of a fundamental misunderstanding of the way that <code>render</code> works.</p><p>For example, here's some code that will trigger this error:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
def show
@book = Book.find(params[:id])
if @book.special?
render action: "special_show"
end
render action: "regular_show"
end
</pre>
</div>
<p>If <code>@book.special?</code> evaluates to <code>true</code>, Rails will start the rendering process to dump the <code>@book</code> variable into the <code>special_show</code> view. But this will <em>not</em> stop the rest of the code in the <code>show</code> action from running, and when Rails hits the end of the action, it will start to render the <code>regular_show</code> view - and throw an error. The solution is simple: make sure that you have only one call to <code>render</code> or <code>redirect</code> in a single code path. One thing that can help is <code>and return</code>. Here's a patched version of the method:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
def show
@book = Book.find(params[:id])
if @book.special?
render action: "special_show" and return
end