This repository has been archived by the owner on Jan 7, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlayouts_and_rendering.html
1573 lines (1437 loc) · 76.7 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 PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Ruby on Rails Guides: Layouts and Rendering in Rails</title>
<link rel="stylesheet" type="text/css" href="stylesheets/style.css" />
<link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print" />
<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shCore.css" />
<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shThemeRailsGuides.css" />
</head>
<body class="guide">
<div id="topNav">
<div class="wrapper">
<strong>More at <a href="http://rubyonrails.org/">rubyonrails.org:</a> </strong>
<a href="http://rubyonrails.org/">Overview</a> |
<a href="http://rubyonrails.org/download">Download</a> |
<a href="http://rubyonrails.org/deploy">Deploy</a> |
<a href="http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/overview">Code</a> |
<a href="http://rubyonrails.org/screencasts">Screencasts</a> |
<a href="http://rubyonrails.org/documentation">Documentation</a> |
<a href="http://rubyonrails.org/ecosystem">Ecosystem</a> |
<a href="http://rubyonrails.org/community">Community</a> |
<a href="http://weblog.rubyonrails.org/">Blog</a>
</div>
</div>
<div id="header">
<div class="wrapper clearfix">
<h1><a href="index.html" title="Return to home page">Guides.rubyonrails.org</a></h1>
<p class="hide"><a href="#mainCol">Skip navigation</a>.</p>
<ul class="nav">
<li><a href="index.html">홈</a></li>
<li class="index"><a href="index.html" onclick="guideMenu(); return false;" id="guidesMenu">목차</a>
<div id="guides" class="clearfix" style="display: none;">
<hr />
<dl class="L">
<dt>시작</dt>
<dd><a href="getting_started.html">레일즈 시작하기</a></dd>
<dt>모델(Models)</dt>
<dd><a href="migrations.html">레일즈 데이터베이스 마이그레이션</a></dd>
<dd><a href="active_record_validations_callbacks.html">액티브 레코드 데이터 검증(Validation)과 Callback(콜백)</a></dd>
<dd><a href="association_basics.html">액티브 레코드 Association(관계)</a></dd>
<dd><a href="active_record_querying.html">액티브 레코드 쿼리 인터페이스</a></dd>
<dt>뷰(Views)</dt>
<dd><a href="layouts_and_rendering.html">레이아웃(Layouts)과 렌더링(Rendering)</a></dd>
<dd><a href="form_helpers.html">액션 뷰 폼 핼퍼(Action View Form Helpers)</a></dd>
<dt>컨트롤러(Controllers)</dt>
<dd><a href="action_controller_overview.html">액션 컨트롤러 둘러보기</a></dd>
<dd><a href="routing.html">외부 요청에 대한 레일즈 라우팅</a></dd>
</dl>
<dl class="R">
<dt>심화내용</dt>
<dd><a href="active_support_core_extensions.html">액티브 서포트(Active Support) 확장(Core Extensions)</a></dd>
<dd><a href="i18n.html">레일즈 국제화I(nternationalization) API</a></dd>
<dd><a href="action_mailer_basics.html">액션 메일러의 기본</a></dd>
<dd><a href="testing.html">레일즈 어플리케이션 테스트하기</a></dd>
<dd><a href="security.html">레일즈 어플리케이션의 보안</a></dd>
<dd><a href="debugging_rails_applications.html">레일즈 어플리케이션 디버깅</a></dd>
<dd><a href="performance_testing.html">레일즈 어플리케이션 성능 테스트하기</a></dd>
<dd><a href="configuring.html">레일즈 어플리케이션 설정</a></dd>
<dd><a href="command_line.html">레일즈 커멘드라인 도구와 Rake 테스크</a></dd>
<dd><a href="caching_with_rails.html">레일즈를 이용한 캐싱</a></dd>
<dt>레일즈 확장하기(Extending Rails)</dt>
<dd><a href="plugins.html">레일즈 플러그인 작성의 기본</a></dd>
<dd><a href="rails_on_rack.html">렉 위의 레일즈(Rails on Rack)</a></dd>
<dd><a href="generators.html">레일즈 제너레이터(Generator) 제작과 수정</a></dd>
<dt>루비 온 레이즈에 기여하기</dt>
<dd><a href="contributing_to_ruby_on_rails.html">루비 온 레이즈에 기여하기</a></dd>
<dd><a href="api_documentation_guidelines.html">API 문서 가이드라인</a></dd>
<dd><a href="ruby_on_rails_guides_guidelines.html">루비 온 레일즈 가이드에 대한 가이드라인</a></dd>
<dt>Release Notes</dt>
<dd><a href="3_0_release_notes.html">Ruby on Rails 3.0 Release Notes</a></dd>
<dd><a href="2_3_release_notes.html">Ruby on Rails 2.3 Release Notes</a></dd>
<dd><a href="2_2_release_notes.html">Ruby on Rails 2.2 Release Notes</a></dd>
</dl>
</div>
</li>
<li><a href="contribute.html">기여하기</a></li>
<li><a href="credits.html">수고하신 분들</a></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. By referring to this guide, you will be able to:</p>
<ul>
<li>Use the various rendering methods built into Rails</li>
<li>Create layouts with multiple content sections</li>
<li>Use partials to <span class="caps">DRY</span> up your views</li>
<li>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 <tt>render</tt></a></li> <li><a href="#using-redirect_to">Using <tt>redirect_to</tt></a></li> <li><a href="#using-head-to-build-header-only-responses">Using <tt>head</tt> To Build Header-Only Responses</a></li></ul></li><li><a href="#structuring-layouts">Structuring Layouts</a><ul><li><a href="#asset-tags">Asset Tags</a></li> <li><a href="#understanding-yield">Understanding <tt>yield</tt></a></li> <li><a href="#using-content_for">Using <tt>content_for</tt></a></li> <li><a href="#using-partials">Using Partials</a></li> <li><a href="#using-nested-layouts">Using Nested Layouts</a></li></ul></li><li><a href="#changelog">Changelog</a></li></ol></div>
</div>
</div>
<div id="container">
<div class="wrapper">
<div id="mainCol">
<h3 id="overview-how-the-pieces-fit-together">1 Overview: How the Pieces Fit Together</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">2 Creating Responses</h3>
<p>From the controller’s point of view, there are three ways to create an <span class="caps">HTTP</span> response:</p>
<ul>
<li>Call <tt>render</tt> to create a full response to send back to the browser</li>
<li>Call <tt>redirect_to</tt> to send an <span class="caps">HTTP</span> redirect status code to the browser</li>
<li>Call <tt>head</tt> to create a response consisting solely of <span class="caps">HTTP</span> headers to send back to the browser</li>
</ul>
<p>I’ll cover each of these methods in turn. But first, a few words about the very easiest thing that the controller can do to create a response: nothing at all.</p>
<h4 id="rendering-by-default-convention-over-configuration-in-action">2.1 Rendering by Default: Convention Over Configuration in Action</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 <tt>BooksController</tt> class:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class BooksController < ApplicationController
end
</pre>
</div>
</notextile>
<p>And the following in your routes file:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
resources :books
</pre>
</div>
</notextile>
<p>And you have a view file <tt>app/views/books/index.html.erb</tt>:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
<h1>Books are coming soon!</h1>
</pre>
</div>
</notextile>
<p>Rails will automatically render <tt>app/views/books/index.html.erb</tt> when you navigate to <tt>/books</tt> 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 <tt>Book</tt> model and add the index action to <tt>BooksController</tt>:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class BooksController < ApplicationController
def index
@books = Book.all
end
end
</pre>
</div>
</notextile>
<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 <tt>action_name.html.erb</tt> template in the controller’s view path and render it. So in this case, Rails will render the <tt>app/views/books/index.html.erb</tt> file.</p>
<p>If we want to display the properties of all the books in our view, we can do so with an <span class="caps">ERB</span> template like this:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
<h1>Listing Books</h1>
<table>
<tr>
<th>Title</th>
<th>Summary</th>
<th></th>
<th></th>
<th></th>
</tr>
<% @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 'Remove', book, :confirm => 'Are you sure?', :method => :delete %></td>
</tr>
<% end %>
</table>
<br />
<%= link_to 'New book', new_book_path %>
</pre>
</div>
</notextile>
<div class='note'><p>The actual rendering is done by subclasses of <tt>ActionView::TemplateHandlers</tt>. 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. In Rails 2, the standard extensions are <tt>.erb</tt> for <span class="caps">ERB</span> (<span class="caps">HTML</span> with embedded Ruby), <tt>.rjs</tt> for <span class="caps">RJS</span> (JavaScript with embedded ruby) and <tt>.builder</tt> for Builder (<span class="caps">XML</span> generator).</p></div>
<h4 id="using-render">2.2 Using <tt>render</tt></h4>
<p>In most cases, the <tt>ActionController::Base#render</tt> method does the heavy lifting of rendering your application’s content for use by a browser. There are a variety of ways to customise the behaviour of <tt>render</tt>. 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, <span class="caps">JSON</span>, or <span class="caps">XML</span>. You can specify the content type or <span class="caps">HTTP</span> status of the rendered response as well.</p>
<div class='info'><p>If you want to see the exact results of a call to <tt>render</tt> without needing to inspect it in a browser, you can call <tt>render_to_string</tt>. This method takes exactly the same options as <tt>render</tt>, but it returns a string instead of sending a response back to the browser.</p></div>
<h5 id="rendering-nothing">2.2.1 Rendering Nothing</h5>
<p>Perhaps the simplest thing you can do with <tt>render</tt> is to render nothing at all:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
render :nothing => true
</pre>
</div>
</notextile>
<p>If you look at the response for this using cURL, you will see the following:</p>
<notextile>
<div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ curl -i 127.0.0.1:3000/books
HTTP/1.1 200 OK
Connection: close
Date: Sun, 24 Jan 2010 09:25:18 GMT
Transfer-Encoding: chunked
Content-Type: */*; charset=utf-8
X-Runtime: 0.014297
Set-Cookie: _blog_session=...snip...; path=/; HttpOnly
Cache-Control: no-cache
$
</pre>
</div>
</notextile>
<p>We see there is an empty response (no data after the <tt>Cache-Control</tt> line), but the request was successful because Rails has set the response to 200 OK. You can set the <tt>:status</tt> option on render to change this response. Rendering nothing can be useful for <span class="caps">AJAX</span> requests where all you want to send back to the browser is an acknowledgement that the request was completed.</p>
<div class='info'><p>You should probably be using the <tt>head</tt> method, discussed later in this guide, instead of <tt>render :nothing</tt>. This provides additional flexibility and makes it explicit that you’re only generating <span class="caps">HTTP</span> headers.</p></div>
<h5 id="rendering-an-action-s-view">2.2.2 Rendering an Action’s View</h5>
<p>If you want to render the view that corresponds to a different action within the same template, you can use <tt>render</tt> with the name of the view:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
def update
@book = Book.find(params[:id])
if @book.update_attributes(params[:book])
redirect_to(@book)
else
render "edit"
end
end
</pre>
</div>
</notextile>
<p>If the call to <tt>update_attributes</tt> fails, calling the <tt>update</tt> action in this controller will render the <tt>edit.html.erb</tt> 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>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
def update
@book = Book.find(params[:id])
if @book.update_attributes(params[:book])
redirect_to(@book)
else
render :edit
end
end
</pre>
</div>
</notextile>
<p>To be explicit, you can use <tt>render</tt> with the <tt>:action</tt> option (though this is no longer necessary in Rails 3.0):</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
def update
@book = Book.find(params[:id])
if @book.update_attributes(params[:book])
redirect_to(@book)
else
render :action => "edit"
end
end
</pre>
</div>
</notextile>
<div class='warning'><p>Using <tt>render</tt> with <tt>:action</tt> is a frequent source of confusion for Rails newcomers. The specified action is used to determine which view to render, but Rails does <em>not</em> run any of the code for that action in the controller. Any instance variables that you require in the view must be set up in the current action before calling <tt>render</tt>.</p></div>
<h5 id="rendering-an-action-s-template-from-another-controller">2.2.3 Rendering an Action’s Template from Another Controller</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 <tt>render</tt>, which accepts the full path (relative to <tt>app/views</tt>) of the template to render. For example, if you’re running code in an <tt>AdminProductsController</tt> that lives in <tt>app/controllers/admin</tt>, you can render the results of an action to a template in <tt>app/views/products</tt> this way:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
render 'products/show'
</pre>
</div>
</notextile>
<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 <tt>:template</tt> option (which was required on Rails 2.2 and earlier):</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
render :template => 'products/show'
</pre>
</div>
</notextile>
<h5 id="rendering-an-arbitrary-file">2.2.4 Rendering an Arbitrary File</h5>
<p>The <tt>render</tt> method can also use a view that’s entirely outside of your application (perhaps you’re sharing views between two Rails applications):</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
render "/u/apps/warehouse_app/current/app/views/products/show"
</pre>
</div>
</notextile>
<p>Rails determines that this is a file render because of the leading slash character. To be explicit, you can use the <tt>:file</tt> option (which was required on Rails 2.2 and earlier):</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
render :file =>
"/u/apps/warehouse_app/current/app/views/products/show"
</pre>
</div>
</notextile>
<p>The <tt>:file</tt> option takes an absolute file-system path. Of course, you need to have rights to the view that you’re using to render the content.</p>
<div class='note'><p>By default, the file is rendered without using the current layout. If you want Rails to put the file into the current layout, you need to add the <tt>:layout => true</tt> option.</p></div>
<div class='info'><p>If you’re running Rails on Microsoft Windows, you should use the <tt>:file</tt> option to render a file, because Windows filenames do not have the same format as Unix filenames.</p></div>
<h5 id="wrapping-it-up">2.2.5 Wrapping it up</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 <tt>edit.html.erb</tt> template in the <tt>views/books</tt> directory:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
render :edit
render :action => :edit
render 'edit'
render 'edit.html.erb'
render :action => 'edit'
render :action => 'edit.html.erb'
render 'books/edit'
render 'books/edit.html.erb'
render :template => 'books/edit'
render :template => 'books/edit.html.erb'
render '/path/to/rails/app/views/books/edit'
render '/path/to/rails/app/views/books/edit.html.erb'
render :file => '/path/to/rails/app/views/books/edit'
render :file => '/path/to/rails/app/views/books/edit.html.erb'
</pre>
</div>
</notextile>
<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">2.2.6 Using <tt>render</tt> with <tt>:inline</tt></h5>
<p>The <tt>render</tt> method can do without a view completely, if you’re willing to use the <tt>:inline</tt> option to supply <span class="caps">ERB</span> as part of the method call. This is perfectly valid:</p>
<notextile>
<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>
</notextile>
<div class='warning'><p>There is seldom any good reason to use this option. Mixing <span class="caps">ERB</span> into your controllers defeats the <span class="caps">MVC</span> 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 <span class="caps">ERB</span>. You can force it to use Builder instead with the <tt>:type</tt> option:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
render :inline =>
"xml.p {'Horrid coding practice!'}", :type => :builder
</pre>
</div>
</notextile>
<h5 id="using-render-with-update">2.2.7 Using <tt>render</tt> with <tt>:update</tt></h5>
<p>You can also render JavaScript-based page updates inline using the <tt>:update</tt> option to <tt>render</tt>:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
render :update do |page|
page.replace_html 'warning', "Invalid options supplied"
end
</pre>
</div>
</notextile>
<div class='warning'><p>Placing JavaScript updates in your controller may seem to streamline small updates, but it defeats the <span class="caps">MVC</span> orientation of Rails and will make it harder for other developers to follow the logic of your project. We recommend using a separate <span class="caps">RJS</span> template instead, no matter how small the update.</p></div>
<h5 id="rendering-text">2.2.8 Rendering Text</h5>
<p>You can send plain text – with no markup at all – back to the browser by using the <tt>:text</tt> option to <tt>render</tt>:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
render :text => "OK"
</pre>
</div>
</notextile>
<div class='info'><p>Rendering pure text is most useful when you’re responding to <span class="caps">AJAX</span> or web service requests that are expecting something other than proper <span class="caps">HTML</span>.</p></div>
<div class='note'><p>By default, if you use the <tt>:text</tt> 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 <tt>:layout => true</tt> option.</p></div>
<h5 id="rendering-json">2.2.9 Rendering <span class="caps">JSON</span></h5>
<p><span class="caps">JSON</span> is a JavaScript data format used by many <span class="caps">AJAX</span> libraries. Rails has built-in support for converting objects to <span class="caps">JSON</span> and rendering that <span class="caps">JSON</span> back to the browser:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
render :json => @product
</pre>
</div>
</notextile>
<div class='info'><p>You don’t need to call <tt>to_json</tt> on the object that you want to render. If you use the <tt>:json</tt> option, <tt>render</tt> will automatically call <tt>to_json</tt> for you.</p></div>
<h5 id="rendering-xml">2.2.10 Rendering <span class="caps">XML</span></h5>
<p>Rails also has built-in support for converting objects to <span class="caps">XML</span> and rendering that <span class="caps">XML</span> back to the caller:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
render :xml => @product
</pre>
</div>
</notextile>
<div class='info'><p>You don’t need to call <tt>to_xml</tt> on the object that you want to render. If you use the <tt>:xml</tt> option, <tt>render</tt> will automatically call <tt>to_xml</tt> for you.</p></div>
<h5 id="rendering-vanilla-javascript">2.2.11 Rendering Vanilla JavaScript</h5>
<p>Rails can render vanilla JavaScript (as an alternative to using <tt>update</tt> with an <tt>.rjs</tt> file):</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
render :js => "alert('Hello Rails');"
</pre>
</div>
</notextile>
<p>This will send the supplied string to the browser with a <span class="caps">MIME</span> type of <tt>text/javascript</tt>.</p>
<h5 id="options-for-render">2.2.12 Options for <tt>render</tt></h5>
<p>Calls to the <tt>render</tt> method generally accept four options:</p>
<ul>
<li><tt>:content_type</tt></li>
<li><tt>:layout</tt></li>
<li><tt>:status</tt></li>
<li><tt>:location</tt></li>
</ul>
<h6 id="the-content_type-option">2.2.12.1 The <tt>:content_type</tt> Option</h6>
<p>By default, Rails will serve the results of a rendering operation with the <span class="caps">MIME</span> content-type of <tt>text/html</tt> (or <tt>application/json</tt> if you use the <tt>:json</tt> option, or <tt>application/xml</tt> for the <tt>:xml</tt> option.). There are times when you might like to change this, and you can do so by setting the <tt>:content_type</tt> option:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
render :file => filename, :content_type => 'application/rss'
</pre>
</div>
</notextile>
<h6 id="the-layout-option">2.2.12.2 The <tt>:layout</tt> Option</h6>
<p>With most of the options to <tt>render</tt>, 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 <tt>:layout</tt> option to tell Rails to use a specific file as the layout for the current action:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
render :layout => 'special_layout'
</pre>
</div>
</notextile>
<p>You can also tell Rails to render with no layout at all:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
render :layout => false
</pre>
</div>
</notextile>
<h6 id="the-status-option">2.2.12.3 The <tt>:status</tt> Option</h6>
<p>Rails will automatically generate a response with the correct <span class="caps">HTML</span> status code (in most cases, this is <tt>200 OK</tt>). You can use the <tt>:status</tt> option to change this:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
render :status => 500
render :status => :forbidden
</pre>
</div>
</notextile>
<p>Rails understands both numeric status codes and symbols for status codes.</p>
<h6 id="the-location-option">2.2.12.4 The <tt>:location</tt> Option</h6>
<p>You can use the <tt>:location</tt> option to set the <span class="caps">HTTP</span> <tt>Location</tt> header:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
render :xml => photo, :location => photo_url(photo)
</pre>
</div>
</notextile>
<h5 id="finding-layouts">2.2.13 Finding Layouts</h5>
<p>To find the current layout, Rails first looks for a file in <tt>app/views/layouts</tt> with the same base name as the controller. For example, rendering actions from the <tt>PhotosController</tt> class will use <tt>app/views/layouts/photos.html.erb</tt> (or <tt>app/views/layouts/photos.builder</tt>). If there is no such controller-specific layout, Rails will use <tt>app/views/layouts/application.html.erb</tt> or <tt>app/views/layouts/application.builder</tt>. If there is no <tt>.erb</tt> layout, Rails will use a <tt>.builder</tt> 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-on-a-per-controller-basis">2.2.13.1 Specifying Layouts on a per-Controller Basis</h6>
<p>You can override the automatic layout conventions in your controllers by using the <tt>layout</tt> declaration in the controller. For example:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class ProductsController < ApplicationController
layout "inventory"
#...
end
</pre>
</div>
</notextile>
<p>With this declaration, all methods within <tt>ProductsController</tt> will use <tt>app/views/layouts/inventory.html.erb</tt> for their layout.</p>
<p>To assign a specific layout for the entire application, use a declaration in your <tt>ApplicationController</tt> class:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class ApplicationController < ActionController::Base
layout "main"
#...
end
</pre>
</div>
</notextile>
<p>With this declaration, all views in the entire application will use <tt>app/views/layouts/main.html.erb</tt> for their layout.</p>
<h6 id="choosing-layouts-at-runtime">2.2.13.2 Choosing Layouts at Runtime</h6>
<p>You can use a symbol to defer the choice of layout until a request is processed:</p>
<notextile>
<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>
</notextile>
<p>Now, if the current user is a special user, they’ll get a special layout when viewing a product. You can even use an inline method to determine the layout:</p>
<p>You can also decide the layout by passing a Proc object, the block you give the Proc will be given the <tt>controller</tt> instance, so you can make decisions based on the current request. For example:</p>
<notextile>
<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>
</notextile>
<h6 id="conditional-layouts">2.2.13.3 Conditional Layouts</h6>
<p>Layouts specified at the controller level support <tt>:only</tt> and <tt>:except</tt> options that take either a method name or an array of method names which correspond to method names within the controller:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class ProductsController < ApplicationController
layout "product", :except => [:index, :rss]
end
</pre>
</div>
</notextile>
<p>With this declaration, the <tt>product</tt> layout would be used for everything but the <tt>rss</tt> and <tt>index</tt> methods.</p>
<h6 id="layout-inheritance">2.2.13.4 Layout Inheritance</h6>
<p>Layouts are shared downwards in the hierarchy, and more specific layouts always override more general ones. For example:</p>
<ul>
<li><tt>application_controller.rb</tt></li>
</ul>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class ApplicationController < ActionController::Base
layout "main"
end
</pre>
</div>
</notextile>
<ul>
<li><tt>posts_controller.rb</tt></li>
</ul>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class PostsController < ApplicationController
end
</pre>
</div>
</notextile>
<ul>
<li><tt>special_posts_controller.rb</tt></li>
</ul>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class SpecialPostsController < PostsController
layout "special"
end
</pre>
</div>
</notextile>
<ul>
<li><tt>old_posts_controller.rb</tt></li>
</ul>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class OldPostsController < SpecialPostsController
layout nil
def show
@post = Post.find(params[:id])
end
def index
@old_posts = Post.older
render :layout => "old"
end
# ...
end
</pre>
</div>
</notextile>
<p>In this application:</p>
<ul>
<li>In general, views will be rendered in the <tt>main</tt> layout</li>
<li><tt>PostsController#index</tt> will use the <tt>main</tt> layout</li>
<li><tt>SpecialPostsController#index</tt> will use the <tt>special</tt> layout</li>
<li><tt>OldPostsController#show</tt> will use no layout at all</li>
<li><tt>OldPostsController#index</tt> will use the <tt>old</tt> layout</li>
</ul>
<h5 id="avoiding-double-render-errors">2.2.14 Avoiding Double Render Errors</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 <tt>render</tt> works.</p>
<p>For example, here’s some code that will trigger this error:</p>
<notextile>
<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>
</notextile>
<p>If <tt>@book.special?</tt> evaluates to <tt>true</tt>, Rails will start the rendering process to dump the <tt>@book</tt> variable into the <tt>special_show</tt> view. But this will <em>not</em> stop the rest of the code in the <tt>show</tt> action from running, and when Rails hits the end of the action, it will start to render the <tt>regular_show</tt> view – and throw an error. The solution is simple: make sure that you have only one call to <tt>render</tt> or <tt>redirect</tt> in a single code path. One thing that can help is <tt>and return</tt>. Here’s a patched version of the method:</p>
<notextile>
<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
render :action => "regular_show"
end
</pre>
</div>
</notextile>
<p>Make sure you use <tt>and return</tt> and not <tt>&& return</tt> because while the former will work, the latter will not due to operator precedence in the Ruby Language.</p>
<p>Note that the implicit render done by ActionController detects if <tt>render</tt> has been called, and thus avoids this error. Therefore, the following will work without errors:</p>
<notextile>
<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
end
</pre>
</div>
</notextile>
<p>This will render a book with <tt>special?</tt> set with the <tt>special_show</tt> template, while other books will render with the default <tt>show</tt> template.</p>
<h4 id="using-redirect_to">2.3 Using <tt>redirect_to</tt></h4>
<p>Another way to handle returning responses to an <span class="caps">HTTP</span> request is with <tt>redirect_to</tt>. As you’ve seen, <tt>render</tt> tells Rails which view (or other asset) to use in constructing a response. The <tt>redirect_to</tt> method does something completely different: it tells the browser to send a new request for a different <span class="caps">URL</span>. For example, you could redirect from wherever you are in your code to the index of photos in your application with this call:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
redirect_to photos_path
</pre>
</div>
</notextile>
<p>You can use <tt>redirect_to</tt> with any arguments that you could use with <tt>link_to</tt> or <tt>url_for</tt>. In addition, there’s a special redirect that sends the user back to the page they just came from:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
redirect_to :back
</pre>
</div>
</notextile>
<h5 id="getting-a-different-redirect-status-code">2.3.1 Getting a Different Redirect Status Code</h5>
<p>Rails uses <span class="caps">HTTP</span> status code 302 (temporary redirect) when you call <tt>redirect_to</tt>. If you’d like to use a different status code (perhaps 301, permanent redirect), you can do so by using the <tt>:status</tt> option:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
redirect_to photos_path, :status => 301
</pre>
</div>
</notextile>
<p>Just like the <tt>:status</tt> option for <tt>render</tt>, <tt>:status</tt> for <tt>redirect_to</tt> accepts both numeric and symbolic header designations.</p>
<h5 id="the-difference-between-render-and-redirect_to">2.3.2 The Difference Between <tt>render</tt> and <tt>redirect_to</tt></h5>
<p>Sometimes inexperienced developers conceive of <tt>redirect_to</tt> as a sort of <tt>goto</tt> command, moving execution from one place to another in your Rails code. This is <em>not</em> correct. Your code stops running and waits for a new request for the browser. It just happens that you’ve told the browser what request it should make next, by sending back an <span class="caps">HTTP</span> 302 status code.</p>
<p>Consider these actions to see the difference:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
def index
@books = Book.all
end
def show
@book = Book.find_by_id(params[:id])
if @book.nil?
render :action => "index"
end
end
</pre>
</div>
</notextile>
<p>With the code in this form, there will likely be a problem if the <tt>@book</tt> variable is <tt>nil</tt>. Remember, a <tt>render :action</tt> doesn’t run any code in the target action, so nothing will set up the <tt>@books</tt> variable that the <tt>index</tt> view is presumably depending on. One way to fix this is to redirect instead of rendering:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
def index
@books = Book.all
end
def show
@book = Book.find_by_id(params[:id])
if @book.nil?
redirect_to :action => :index
end
end
</pre>
</div>
</notextile>
<p>With this code, the browser will make a fresh request for the index page, the code in the <tt>index</tt> method will run, and all will be well.</p>
<p>The only downside to this code, is that it requires a round trip to the browser, the browser requested the show action with <tt>/books/1</tt> and the controller finds that there are no books, so the controller sends out a 302 redirect response to the browser telling it to go to <tt>/books/</tt>, the browser complies and sends a new request back to the controller asking now for the <tt>index</tt> action, the controller then gets all the books in the database and renders the index template, sending it back down to the browser which then shows it on your screen.</p>
<p>While in a small app, this added latency might not be a problem, it is something to think about when speed of response is of the essence. One way to handle this double request (though a contrived example) could be:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
def index
@books = Book.all
end
def show
@book = Book.find_by_id(params[:id])
if @book.nil?
@books = Book.all
render "index", :alert => 'Your book was not found!'
end
end
</pre>
</div>
</notextile>
<p>Which would detect that there are no books, populate the <tt>@books</tt> instance variable with all the books in the database and then directly render the <tt>index.html.erb</tt> template returning it to the browser with a flash alert message telling the user what happened.</p>
<h4 id="using-head-to-build-header-only-responses">2.4 Using <tt>head</tt> To Build Header-Only Responses</h4>
<p>The <tt>head</tt> method can be used to send responses with only headers to the browser. It provides a more obvious alternative to calling <tt>render :nothing</tt>. The <tt>head</tt> method takes one parameter, which is interpreted as a hash of header names and values. For example, you can return only an error header:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
head :bad_request
</pre>
</div>
</notextile>
<p>Which would produce the following header:</p>
<notextile>
<div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
HTTP/1.1 400 Bad Request
Connection: close
Date: Sun, 24 Jan 2010 12:15:53 GMT
Transfer-Encoding: chunked
Content-Type: text/html; charset=utf-8
X-Runtime: 0.013483
Set-Cookie: _blog_session=...snip...; path=/; HttpOnly
Cache-Control: no-cache
</pre>
</div>
</notextile>
<p>Or you can use other <span class="caps">HTTP</span> headers to convey additional information:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
head :created, :location => photo_path(@photo)
</pre>
</div>
</notextile>
<p>Which would produce:</p>
<notextile>
<div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
HTTP/1.1 201 Created
Connection: close
Date: Sun, 24 Jan 2010 12:16:44 GMT
Transfer-Encoding: chunked
Location: /photos/1
Content-Type: text/html; charset=utf-8
X-Runtime: 0.083496
Set-Cookie: _blog_session=...snip...; path=/; HttpOnly
Cache-Control: no-cache
</pre>
</div>
</notextile>
<h3 id="structuring-layouts">3 Structuring Layouts</h3>
<p>When Rails renders a view as a response, it does so by combining the view with the current layout (using the rules for finding the current layout that were covered earlier in this guide). Within a layout, you have access to three tools for combining different bits of output to form the overall response:</p>
<ul>
<li>Asset tags</li>
<li><tt>yield</tt> and <tt>content_for</tt></li>
<li>Partials</li>
</ul>
<h4 id="asset-tags">3.1 Asset Tags</h4>
<p>Asset tags provide methods for generating <span class="caps">HTML</span> that links views to feeds, JavaScript, stylesheets, images, videos and audios. These are the six asset tags available in Rails:</p>
<ul>
<li><tt>auto_discovery_link_tag</tt></li>
<li><tt>javascript_include_tag</tt></li>
<li><tt>stylesheet_link_tag</tt></li>
<li><tt>image_tag</tt></li>
<li><tt>video_tag</tt></li>
<li><tt>audio_tag</tt></li>
</ul>
<p>You can use these tags in layouts or other views, although the tags other than <tt>image_tag</tt> are most commonly used in the <tt><head></tt> section of a layout.</p>
<div class='warning'><p>The asset tags do <em>not</em> verify the existence of the assets at the specified locations; they simply assume that you know what you’re doing and generate the link.</p></div>
<h5 id="linking-to-feeds-with-auto_discovery_link_tag">3.1.1 Linking to Feeds with <tt>auto_discovery_link_tag</tt></h5>
<p>The <tt>auto_discovery_link_tag</tt> helper builds <span class="caps">HTML</span> that most browsers and newsreaders can use to detect the presences of <span class="caps">RSS</span> or <span class="caps">ATOM</span> feeds. It takes the type of the link (<tt>:rss</tt> or <tt>:atom</tt>), a hash of options that are passed through to url_for, and a hash of options for the tag:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= auto_discovery_link_tag(:rss, {:action => "feed"},
{:title => "RSS Feed"}) %>
</pre>
</div>
</notextile>
<p>There are three tag options available for <tt>auto_discovery_link_tag</tt>:</p>
<ul>
<li><tt>:rel</tt> specifies the <tt>rel</tt> value in the link (defaults to “alternate”)</li>
<li><tt>:type</tt> specifies an explicit <span class="caps">MIME</span> type. Rails will generate an appropriate <span class="caps">MIME</span> type automatically.</li>
<li><tt>:title</tt> specifies the title of the link</li>
</ul>
<h5 id="linking-to-javascript-files-with-javascript_include_tag">3.1.2 Linking to JavaScript Files with <tt>javascript_include_tag</tt></h5>
<p>The <tt>javascript_include_tag</tt> helper returns an <span class="caps">HTML</span> <tt>script</tt> tag for each source provided. Rails looks in <tt>public/javascripts</tt> for these files by default, but you can specify a full path relative to the document root, or a <span class="caps">URL</span>, if you prefer. For example, to include <tt>public/javascripts/main.js</tt>:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= javascript_include_tag "main" %>
</pre>
</div>
</notextile>
<p>To include <tt>public/javascripts/main.js</tt> and <tt>public/javascripts/columns.js</tt>:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= javascript_include_tag "main", "columns" %>
</pre>
</div>
</notextile>
<p>To include <tt>public/javascripts/main.js</tt> and <tt>public/photos/columns.js</tt>:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= javascript_include_tag "main", "/photos/columns" %>
</pre>
</div>
</notextile>
<p>To include <tt>http://example.com/main.js</tt>:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= javascript_include_tag "http://example.com/main.js" %>
</pre>
</div>
</notextile>
<p>The <tt>defaults</tt> option loads the Prototype and Scriptaculous libraries:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= javascript_include_tag :defaults %>
</pre>
</div>
</notextile>
<p>The <tt>all</tt> option loads every JavaScript file in <tt>public/javascripts</tt>, starting with the Prototype and Scriptaculous libraries:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= javascript_include_tag :all %>
</pre>
</div>
</notextile>
<p>You can supply the <tt>:recursive</tt> option to load files in subfolders of <tt>public/javascripts</tt> as well:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= javascript_include_tag :all, :recursive => true %>
</pre>
</div>
</notextile>
<p>If you’re loading multiple JavaScript files, you can create a better user experience by combining multiple files into a single download. To make this happen in production, specify <tt>:cache => true</tt> in your <tt>javascript_include_tag</tt>:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= javascript_include_tag "main", "columns", :cache => true %>
</pre>
</div>
</notextile>
<p>By default, the combined file will be delivered as <tt>javascripts/all.js</tt>. You can specify a location for the cached asset file instead:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= javascript_include_tag "main", "columns",
:cache => 'cache/main/display' %>
</pre>
</div>
</notextile>
<p>You can even use dynamic paths such as <tt>cache/#{current_site}/main/display</tt>.</p>
<h5 id="linking-to-css-files-with-stylesheet_link_tag">3.1.3 Linking to <span class="caps">CSS</span> Files with <tt>stylesheet_link_tag</tt></h5>
<p>The <tt>stylesheet_link_tag</tt> helper returns an <span class="caps">HTML</span> <tt><link></tt> tag for each source provided. Rails looks in <tt>public/stylesheets</tt> for these files by default, but you can specify a full path relative to the document root, or a <span class="caps">URL</span>, if you prefer. For example, to include <tt>public/stylesheets/main.css</tt>:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= stylesheet_link_tag "main" %>
</pre>
</div>
</notextile>
<p>To include <tt>public/stylesheets/main.css</tt> and <tt>public/stylesheets/columns.css</tt>:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= stylesheet_link_tag "main", "columns" %>
</pre>
</div>
</notextile>
<p>To include <tt>public/stylesheets/main.css</tt> and <tt>public/photos/columns.css</tt>:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= stylesheet_link_tag "main", "/photos/columns" %>
</pre>
</div>
</notextile>
<p>To include <tt>http://example.com/main.css</tt>:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= stylesheet_link_tag "http://example.com/main.css" %>
</pre>
</div>
</notextile>
<p>By default, <tt>stylesheet_link_tag</tt> creates links with <tt>media="screen" rel="stylesheet" type="text/css"</tt>. You can override any of these defaults by specifying an appropriate option (<tt>:media</tt>, <tt>:rel</tt>, or <tt>:type</tt>):</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= stylesheet_link_tag "main_print", :media => "print" %>
</pre>
</div>
</notextile>
<p>The <tt>all</tt> option links every <span class="caps">CSS</span> file in <tt>public/stylesheets</tt>:</p>
<notextile>
<div class="code_container">