-
Notifications
You must be signed in to change notification settings - Fork 0
/
action_view_overview.html
1539 lines (1349 loc) · 87.9 KB
/
action_view_overview.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="zh-TW">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Action View 綜覽 — Ruby on Rails 指南</title>
<meta name="description" content="Ruby on Rails 指南:系統學習 Rails(Rails 4.2 版本)" >
<meta name="keywords" content="Ruby on Rails Guides 指南 中文 學習 免費 網路 Web 開發" >
<meta name="author" content="http://git.io/G_R1sA">
<meta property="fb:admins" content="1340181291">
<meta property="og:title" content="Action View 綜覽 — Ruby on Rails 指南" >
<meta property="og:site_name" content="Ruby on Rails 指南">
<meta property="og:image" content="http://rails.ruby.tw/images/rails_guides_cover.jpg">
<meta property="og:url" content="http://rails.ruby.tw/">
<meta property="og:type" content="article">
<meta property="og:description" content="Ruby on Rails 指南:系統學習 Rails(Rails 4.2 版本)">
<link rel="stylesheet" href="stylesheets/application.css">
<link href="http://fonts.googleapis.com/css?family=Noto+Sans:400,700|Noto+Serif:700|Source+Code+Pro" rel="stylesheet">
<link href="images/favicon.ico" rel="shortcut icon" type="image/x-icon">
</head>
<body class="guide">
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/zh-TW/sdk.js#xfbml=1&appId=837401439623727&version=v2.0";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<script type="text/javascript">
window.twttr=(function(d,s,id){var t,js,fjs=d.getElementsByTagName(s)[0];if(d.getElementById(id)){return}js=d.createElement(s);js.id=id;js.src="https://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);return window.twttr||(t={_e:[],ready:function(f){t._e.push(f)}})}(document,"script","twitter-wjs"));
</script>
<div id="topNav">
<div class="wrapper">
<strong class="more-info-label">更多內容 <a href="http://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="http://rubyonrails.org/">綜覽</a></li>
<li class="more-info"><a href="http://rubyonrails.org/download">下載</a></li>
<li class="more-info"><a href="http://rubyonrails.org/deploy">部署</a></li>
<li class="more-info"><a href="https://github.com/rails/rails">原始碼</a></li>
<li class="more-info"><a href="http://rubyonrails.org/screencasts">影片</a></li>
<li class="more-info"><a href="http://rubyonrails.org/documentation">文件</a></li>
<li class="more-info"><a href="http://rubyonrails.org/community">社群</a></li>
<li class="more-info"><a href="http://weblog.rubyonrails.org/">Blog</a></li>
</ul>
</div>
</div>
<div id="header">
<div class="wrapper clearfix">
<h1><a href="index.html" title="回首頁">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>
<dl class="L">
<dt>起步走</dt>
<dd><a href="getting_started.html">Rails 起步走</a></dd>
<dt>Models</dt>
<dd><a href="active_record_basics.html">Active Record 基礎</a></dd>
<dd><a href="active_record_migrations.html">Active Record 遷移</a></dd>
<dd><a href="active_record_validations.html">Active Record 驗證</a></dd>
<dd><a href="active_record_callbacks.html">Active Record 回呼</a></dd>
<dd><a href="association_basics.html">Active Record 關聯</a></dd>
<dd><a href="active_record_querying.html">Active Record 查詢</a></dd>
<dt>Views</dt>
<dd><a href="layouts_and_rendering.html">Rails 算繪與版型</a></dd>
<dd><a href="form_helpers.html">Action View 表單輔助方法</a></dd>
<dt>Controllers</dt>
<dd><a href="action_controller_overview.html">Action Controller 綜覽</a></dd>
<dd><a href="routing.html">Rails 路由:深入淺出</a></dd>
</dl>
<dl class="R">
<dt>深入了解</dt>
<dd><a href="active_support_core_extensions.html">Active Support 核心擴展</a></dd>
<dd><a href="i18n.html">Rails 國際化 API</a></dd>
<dd><a href="action_mailer_basics.html">Action Mailer 基礎</a></dd>
<dd><a href="active_job_basics.html">Active Job 基礎</a></dd>
<dd><a href="security.html">Rails 安全指南</a></dd>
<dd><a href="debugging_rails_applications.html">除錯 Rails 應用程式</a></dd>
<dd><a href="configuring.html">Rails 應用程式設定</a></dd>
<dd><a href="command_line.html">Rake 任務與 Rails 命令列工具</a></dd>
<dd><a href="asset_pipeline.html">Asset Pipeline</a></dd>
<dd><a href="working_with_javascript_in_rails.html">在 Rails 使用 JavaScript</a></dd>
<dd><a href="constant_autoloading_and_reloading.html">Constant Autoloading and Reloading</a></dd>
<dt>擴充 Rails</dt>
<dd><a href="rails_on_rack.html">Rails on Rack</a></dd>
<dd><a href="generators.html">客製與新建 Rails 產生器</a></dd>
<dd><a href="rails_application_templates.html">Rails 應用程式模版</a></dd>
<dt>貢獻 Ruby on Rails</dt>
<dd><a href="contributing_to_ruby_on_rails.html">貢獻 Ruby on Rails</a></dd>
<dd><a href="api_documentation_guidelines.html">API 文件準則</a></dd>
<dd><a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails 指南準則</a></dd>
<dt>維護方針</dt>
<dd><a href="maintenance_policy.html">維護方針</a></dd>
<dt>發佈記</dt>
<dd><a href="upgrading_ruby_on_rails.html">升級 Ruby on Rails</a></dd>
<dd><a href="4_2_release_notes.html">Ruby on Rails 4.2 發佈記</a></dd>
<dd><a href="4_1_release_notes.html">Ruby on Rails 4.1 發佈記</a></dd>
<dd><a href="4_0_release_notes.html">Ruby on Rails 4.0 發佈記</a></dd>
<dd><a href="3_2_release_notes.html">Ruby on Rails 3.2 發佈記</a></dd>
<dd><a href="3_1_release_notes.html">Ruby on Rails 3.1 發佈記</a></dd>
<dd><a href="3_0_release_notes.html">Ruby on Rails 3.0 發佈記</a></dd>
<dd><a href="2_3_release_notes.html">Ruby on Rails 2.3 發佈記</a></dd>
<dd><a href="2_2_release_notes.html">Ruby on Rails 2.2 發佈記</a></dd>
<dt>Rails 指南翻譯術語</dt>
<dd><a href="translation_terms.html">翻譯術語</a></dd>
</dl>
</div>
</li>
<li><a class="nav-item" href="//github.com/docrails-tw/guides">貢獻翻譯</a></li>
<li><a class="nav-item" href="contributing_to_ruby_on_rails.html">貢獻</a></li>
<li><a class="nav-item" href="credits.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">Rails 起步走</option>
</optgroup>
<optgroup label="Models">
<option value="active_record_basics.html">Active Record 基礎</option>
<option value="active_record_migrations.html">Active Record 遷移</option>
<option value="active_record_validations.html">Active Record 驗證</option>
<option value="active_record_callbacks.html">Active Record 回呼</option>
<option value="association_basics.html">Active Record 關聯</option>
<option value="active_record_querying.html">Active Record 查詢</option>
</optgroup>
<optgroup label="Views">
<option value="layouts_and_rendering.html">Rails 算繪與版型</option>
<option value="form_helpers.html">Action View 表單輔助方法</option>
</optgroup>
<optgroup label="Controllers">
<option value="action_controller_overview.html">Action Controller 綜覽</option>
<option value="routing.html">Rails 路由:深入淺出</option>
</optgroup>
<optgroup label="深入了解">
<option value="active_support_core_extensions.html">Active Support 核心擴展</option>
<option value="i18n.html">Rails 國際化 API</option>
<option value="action_mailer_basics.html">Action Mailer 基礎</option>
<option value="active_job_basics.html">Active Job 基礎</option>
<option value="security.html">Rails 安全指南</option>
<option value="debugging_rails_applications.html">除錯 Rails 應用程式</option>
<option value="configuring.html">Rails 應用程式設定</option>
<option value="command_line.html">Rake 任務與 Rails 命令列工具</option>
<option value="asset_pipeline.html">Asset Pipeline</option>
<option value="working_with_javascript_in_rails.html">在 Rails 使用 JavaScript</option>
<option value="constant_autoloading_and_reloading.html">Constant Autoloading and Reloading</option>
</optgroup>
<optgroup label="擴充 Rails">
<option value="rails_on_rack.html">Rails on Rack</option>
<option value="generators.html">客製與新建 Rails 產生器</option>
<option value="rails_application_templates.html">Rails 應用程式模版</option>
</optgroup>
<optgroup label="貢獻 Ruby on Rails">
<option value="contributing_to_ruby_on_rails.html">貢獻 Ruby on Rails</option>
<option value="api_documentation_guidelines.html">API 文件準則</option>
<option value="ruby_on_rails_guides_guidelines.html">Ruby on Rails 指南準則</option>
</optgroup>
<optgroup label="維護方針">
<option value="maintenance_policy.html">維護方針</option>
</optgroup>
<optgroup label="發佈記">
<option value="upgrading_ruby_on_rails.html">升級 Ruby on Rails</option>
<option value="4_2_release_notes.html">Ruby on Rails 4.2 發佈記</option>
<option value="4_1_release_notes.html">Ruby on Rails 4.1 發佈記</option>
<option value="4_0_release_notes.html">Ruby on Rails 4.0 發佈記</option>
<option value="3_2_release_notes.html">Ruby on Rails 3.2 發佈記</option>
<option value="3_1_release_notes.html">Ruby on Rails 3.1 發佈記</option>
<option value="3_0_release_notes.html">Ruby on Rails 3.0 發佈記</option>
<option value="2_3_release_notes.html">Ruby on Rails 2.3 發佈記</option>
<option value="2_2_release_notes.html">Ruby on Rails 2.2 發佈記</option>
</optgroup>
<optgroup label="Rails 指南翻譯術語">
<option value="translation_terms.html">翻譯術語</option>
</optgroup>
</select>
</li>
</ul>
</div>
</div>
</div>
<hr class="hide">
<div id="feature">
<div class="wrapper">
<h2>Action View 綜覽</h2><p>讀完本篇,您將了解:</p>
<ul>
<li>什麼是 Action View、如何在 Rails 裡使用。</li>
<li>如何善用模版,局部頁面與版型。</li>
<li>Action View 提供的輔助方法、如何自己寫輔助方法。</li>
<li>如何使用本地化的 View。</li>
<li>如何在 Rails 之外使用 Action View。</li>
</ul>
<div id="subCol">
<h3 class="chapter"><img src="images/chapters_icon.gif" alt="" />Chapters</h3>
<ol class="chapters">
<li><a href="#%E4%BB%80%E9%BA%BC%E6%98%AF-action-view%EF%BC%9F">什麼是 Action View?</a></li>
<li><a href="#%E5%9C%A8-rails-%E4%B8%AD%E4%BD%BF%E7%94%A8-action-view">在 Rails 中使用 Action View</a></li>
<li>
<a href="#%E6%A8%A1%E7%89%88%E3%80%81%E5%B1%80%E9%83%A8%E9%A0%81%E9%9D%A2%E5%8F%8A%E7%89%88%E5%9E%8B">模版、局部頁面及版型</a>
<ul>
<li><a href="#%E6%A8%A1%E7%89%88">模版</a></li>
<li><a href="#%E5%B1%80%E9%83%A8%E9%A0%81%E9%9D%A2">局部頁面</a></li>
<li><a href="#layouts">Layouts</a></li>
</ul>
</li>
<li><a href="#partial-layouts">Partial Layouts</a></li>
<li><a href="#view-paths">View Paths</a></li>
<li>
<a href="#overview-of-helpers-provided-by-action-view">Overview of helpers provided by Action View</a>
<ul>
<li><a href="#recordtaghelper">RecordTagHelper</a></li>
<li><a href="#assettaghelper">AssetTagHelper</a></li>
<li><a href="#atomfeedhelper">AtomFeedHelper</a></li>
<li><a href="#benchmarkhelper">BenchmarkHelper</a></li>
<li><a href="#cachehelper">CacheHelper</a></li>
<li><a href="#capturehelper">CaptureHelper</a></li>
<li><a href="#datehelper">DateHelper</a></li>
<li><a href="#debughelper">DebugHelper</a></li>
<li><a href="#formhelper">FormHelper</a></li>
<li><a href="#formoptionshelper">FormOptionsHelper</a></li>
<li><a href="#formtaghelper">FormTagHelper</a></li>
<li><a href="#javascripthelper">JavaScriptHelper</a></li>
<li><a href="#numberhelper">NumberHelper</a></li>
<li><a href="#sanitizehelper">SanitizeHelper</a></li>
<li><a href="#csrfhelper">CsrfHelper</a></li>
</ul>
</li>
<li><a href="#localized-views">Localized Views</a></li>
</ol>
</div>
</div>
</div>
<div id="container">
<div class="wrapper">
<div id="mainCol">
<h3 id="什麼是-action-view?">1 什麼是 Action View?</h3><p>Action View 與 Action Controller 是 Action Pack 中的兩個主要元件。 在 Rails 裡,網路請求是由 Action Pack 負責處理的。此過程分成處理邏輯的 controller 步驟,及算繪模版的 view 步驟。通常 Action Controller 是與資料庫溝通,根據需求來執行 CRUD 操作。而 Action View 則接著負責編譯出回應。</p><p>Action View 模版是由嵌入 HTML 的 Ruby 撰寫而成。為了避免模版充斥混亂的程式碼,Action View 提供了許多輔助方法,用來撰寫表單、日期及字串等。當應用程式成長時,加入自訂的輔助方法也很容易。</p><div class="note"><p>部份 Action View 的功能與 Active Record 綁在一起。但這不代表 Action View 依賴於 Action Record。Active View 是個獨立的函式庫,可以和其它的 Ruby 函式庫一起使用。</p></div><h3 id="在-rails-中使用-action-view">2 在 Rails 中使用 Action View</h3><p>每個 Controller 在 <code>app/views</code> 中都會有一個對應的資料夾,裡面包含了該 Controller 的模板檔案。這些檔案用來顯示 Controller 各個動作的結果頁面。</p><p>看看 Rails 用 <code>scaffold</code> 命令建立新資源時,預設會產生哪些檔案:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ bin/rails generate scaffold article
[...]
invoke scaffold_controller
create app/controllers/articles_controller.rb
invoke erb
create app/views/articles
create app/views/articles/index.html.erb
create app/views/articles/edit.html.erb
create app/views/articles/show.html.erb
create app/views/articles/new.html.erb
create app/views/articles/_form.html.erb
[...]
</pre>
</div>
<p>Rails 的 View 有命名慣例。通常 View 的檔名和 Controller 的動作同名,如上所示。例如 <code>articles_controller.rb</code> 的 <code>index</code> 動作使用 <code>app/views/articles</code> 資料夾中的 <code>index.html.erb</code> 這個 View 檔案。回傳給用戶端的完整 HTML 是由這個 ERB 檔案、版型,以及其它引用的局部頁面組成。本篇之後會對這三種 View 做更詳細的介紹。</p><h3 id="模版、局部頁面及版型">3 模版、局部頁面及版型</h3><p>上面有提到過,最終輸出的 HTML 由三種 Rails 元素組成:模版、局部頁面以及版型。底下簡單介紹這三種元素。</p><h4 id="模版">3.1 模版</h4><p>Action View 的模版有數種不同的寫法。如果模版的副檔名是 <code>erb</code> 的話,那麼這個模版是混合 ERB (Ruby 內建)和 HTML。若模版的副檔名是 <code>.builder</code>,則是使用了 <code>Builder::XmlMarkup</code> 函式庫。</p><p>Rails 支援多種模版系統,使用副檔名來做區隔。例如使用 ERB 模版系統的 HTML 檔案,副檔名是 <code>.html.erb</code>。</p><h5 id="erb">3.1.1 ERB</h5><p>在 ERB 模版裡,Ruby 程式碼會放在 <code><% %></code> 或是 <code><%= %></code> 標籤裡。<code><% %></code> 標籤是用來執行不會回傳任何值的 Ruby 程式碼,例如條件判斷、迴圈或是區塊等等,而 <code><%= %></code> 標籤則是用來輸出結果。</p><p>考慮以下 <code>names</code> 迴圈:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
<h1>Names of all the people</h1>
<% @people.each do |person| %>
Name: <%= person.name %><br>
<% end %>
</pre>
</div>
<p>迴圈放在普通嵌入標籤(<code><% %></code>)裡,而需要顯示的 <code>name</code> 則是放在會輸出結果的標籤(<code><%= %></code>)中。注意這不是建議的使用方法,Ruby 一般的輸出函式如 <code>print</code> 或是 <code>puts</code> 是無法將結果顯示在 ERB 模版裡。所以以下的範例是不正確的:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
<%# WRONG %>
Hi, Mr. <% puts "Frodo" %>
</pre>
</div>
<p>要去掉開頭或結尾的空白,可以用 <code><%-</code> <code>-%></code> 來取代 <code><%</code> 及 <code>%></code>。</p><h5 id="builder">3.1.2 Builder</h5><p>Builder 模版 ERB 的替代方案,比 ERB 需要更多程式設計。在產生 XML 時特別有用。在副檔名為 <code>.builder</code> 的模版裡,可以直接使用名為 <code>xml</code> 的 <code>XmlMarkup</code> 物件。</p><p>以下是一些簡單的範例:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
xml.em("emphasized")
xml.em { xml.b("emph & bold") }
xml.a("A Link", "href" => "http://rubyonrails.org")
xml.target("name" => "compile", "option" => "fast")
</pre>
</div>
<p>會產生:</p><div class="code_container">
<pre class="brush: xml; gutter: false; toolbar: false">
<em>emphasized</em>
<em><b>emph &amp; bold</b></em>
<a href="http://rubyonrails.org">A link</a>
<target option="fast" name="compile" />
</pre>
</div>
<p>傳入區塊的方法會被當成一個巢狀 XML 標籤的外層,區塊內容則會嵌套成內層的標籤來處理。見下例:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
xml.div {
xml.h1(@person.name)
xml.p(@person.bio)
}
</pre>
</div>
<p>會生成:</p><div class="code_container">
<pre class="brush: xml; gutter: false; toolbar: false">
<div>
<h1>David Heinemeier Hansson</h1>
<p>A product of Danish Design during the Winter of '79...</p>
</div>
</pre>
</div>
<p>以下是一個 Basecamp 中實際用到的完整 RSS 範例:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
xml.rss("version" => "2.0", "xmlns:dc" => "http://purl.org/dc/elements/1.1/") do
xml.channel do
xml.title(@feed_title)
xml.link(@url)
xml.description "Basecamp: Recent items"
xml.language "en-us"
xml.ttl "40"
for item in @recent_items
xml.item do
xml.title(item_title(item))
xml.description(item_description(item)) if item_description(item)
xml.pubDate(item_pubDate(item))
xml.guid(@person.firm.account.url + @recent_items.url(item))
xml.link(@person.firm.account.url + @recent_items.url(item))
xml.tag!("dc:creator", item.author_name) if item_has_creator?(item)
end
end
end
end
</pre>
</div>
<h5 id="模版快取">3.1.3 模版快取</h5><p>Rail 預設會編譯所有的模版來進行算繪。當你修改某個模板後,development 模式下的 Rails 會重新檢查及編譯它。</p><h4 id="局部頁面">3.2 局部頁面</h4><p>局部頁面模板 - 簡稱局部頁面 - 用來把算繪過程拆成更好管理的小片段的工具。有了局部頁面,可以把某些特定內容的算繪移到單獨的檔案。</p><h5 id="局部頁面命名">3.2.1 局部頁面命名</h5><p>在 view 檔案中,你要用 <code>render</code> 來算繪局部頁面</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= render "menu" %>
</pre>
</div>
<p>這樣會在呼叫的地方,找到目前資料夾下的 <code>_meun.html.erb</code> 檔案來算繪。注意名字開頭的"底線" (_): 局部頁面的命名規則是由底線開頭。用來與一般的 view 區別。但在引用局部頁面時,呼叫的語法不用加上底線。如果要呼叫其它資料夾下的局部頁面也是一樣不加底線:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= render "shared/menu" %>
</pre>
</div>
<p>這樣會去找到 <code>app/views/shared/_menu.html.erb</code> 檔案來引入。</p><h5 id="使用局部頁面來簡化-views">3.2.2 使用局部頁面來簡化 Views</h5><p>局部頁面的一個用途是把它拿來當副程式;把細節的部份拆出去,讓你更容易理解 view 的全局。舉例來說,你可能看過長這樣的 view:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
<%= render "shared/ad_banner" %>
<h1>Products</h1>
<p>Here are a few of our fine products:</p>
<% @products.each do |product| %>
<%= render partial: "product", locals: {product: product} %>
<% end %>
<%= render "shared/footer" %>
</pre>
</div>
<p>這裡的 <code>_ad_banner.html.erb</code> 及 <code>_footer.html.erb</code> 局部頁面可以包含你的應用程式裡其它頁面可以共用的內容。這樣一來在寫各個頁面時,就不需要去關注這些瑣碎的細節。</p><h5 id="as-及-object-選項">3.2.3 <code>as</code> 及 <code>object</code> 選項</h5><p><code>ActionView::Partials::PartialRenderer</code> 預設會有個物件,存在與模版名稱相同的變數中。例如:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= render partial: "product" %>
</pre>
</div>
<p>在局部頁面中,我們會把 <code>@product</code> 存在區域變數 <code>product</code> 中。就如同我們寫了:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= render partial: "product", locals: {product: @product} %>
</pre>
</div>
<p>用 <code>as</code> 選項,我們可以改用其它的區域變數名稱。例如當我們想用 <code>item</code> 取代 <code>product</code> 時,我們會這樣寫:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= render partial: "product", as: "item" %>
</pre>
</div>
<p>而 <code>object</code> 選項讓我們可以直接指定要算繪到局部頁面中的物件。這會用於模版頁面的物件存在其它地方時。(例如: 要算繪的物件是另一個實例物件,或是存在某個區域變數裡。)</p><p>例如想用這種方法寫時:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= render partial: "product", locals: {product: @item} %>
</pre>
</div>
<p>我們會改成這樣:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= render partial: "product", object: @item %>
</pre>
</div>
<p><code>object</code> 及 <code>as</code> 選項可以同時用:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= render partial: "product", object: @item, as: "item" %>
</pre>
</div>
<h5 id="rendering-collections">3.2.4 Rendering Collections</h5><p>It is very common that a template needs to iterate over a collection and render a sub-template for each of the elements. This pattern has been implemented as a single method that accepts an array and renders a partial for each one of the elements in the array.</p><p>So this example for rendering all the products:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<% @products.each do |product| %>
<%= render partial: "product", locals: { product: product } %>
<% end %>
</pre>
</div>
<p>can be rewritten in a single line:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= render partial: "product", collection: @products %>
</pre>
</div>
<p>When a partial is called like this (eg. with a collection), the individual instances of the partial have access to the member of the collection being rendered via a variable named after the partial. In this case, the partial is <code>_product</code>, and within it you can refer to <code>product</code> to get the instance that is being rendered.</p><p>You can use a shorthand syntax for rendering collections. Assuming <code>@products</code> is a collection of <code>Product</code> instances, you can simply write the following to produce the same result:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= render @products %>
</pre>
</div>
<p>Rails determines the name of the partial to use by looking at the model name in the collection, <code>Product</code> in this case. In fact, you can even create a heterogeneous collection and render it this way, and Rails will choose the proper partial for each member of the collection.</p><h5 id="spacer-templates">3.2.5 Spacer Templates</h5><p>You can also specify a second partial to be rendered between instances of the main partial by using the <code>:spacer_template</code> option:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= render partial: @products, spacer_template: "product_ruler" %>
</pre>
</div>
<p>Rails will render the <code>_product_ruler</code> partial (with no data passed to it) between each pair of <code>_product</code> partials.</p><h4 id="layouts">3.3 Layouts</h4><p>Layouts can be used to render a common view template around the results of Rails controller actions. Typically, every Rails application has a couple of overall layouts that most pages are rendered within. For example, a site might have a layout for a logged in user, and a layout for the marketing or sales side of the site. The logged in user layout might include top-level navigation that should be present across many controller actions. The sales layout for a SaaS app might include top-level navigation for things like "Pricing" and "Contact Us." You would expect each layout to have a different look and feel. You can read more details about Layouts in the <a href="layouts_and_rendering.html">Layouts and Rendering in Rails</a> guide.</p><h3 id="partial-layouts">4 Partial Layouts</h3><p>Partials can have their own layouts applied to them. These layouts are different than the ones that are specified globally for the entire action, but they work in a similar fashion.</p><p>Let's say we're displaying an article on a page, that should be wrapped in a <code>div</code> for display purposes. First, we'll create a new <code>Article</code>:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Article.create(body: 'Partial Layouts are cool!')
</pre>
</div>
<p>In the <code>show</code> template, we'll render the <code>_article</code> partial wrapped in the <code>box</code> layout:</p><p><strong>articles/show.html.erb</strong></p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= render partial: 'article', layout: 'box', locals: {article: @article} %>
</pre>
</div>
<p>The <code>box</code> layout simply wraps the <code>_article</code> partial in a <code>div</code>:</p><p><strong>articles/_box.html.erb</strong></p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
<div class='box'>
<%= yield %>
</div>
</pre>
</div>
<p>The <code>_article</code> partial wraps the article's <code>body</code> in a <code>div</code> with the <code>id</code> of the article using the <code>div_for</code> helper:</p><p><strong>articles/_article.html.erb</strong></p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
<%= div_for(article) do %>
<p><%= article.body %></p>
<% end %>
</pre>
</div>
<p>this would output the following:</p><div class="code_container">
<pre class="brush: xml; gutter: false; toolbar: false">
<div class='box'>
<div id='article_1'>
<p>Partial Layouts are cool!</p>
</div>
</div>
</pre>
</div>
<p>Note that the partial layout has access to the local <code>article</code> variable that was passed into the <code>render</code> call. However, unlike application-wide layouts, partial layouts still have the underscore prefix.</p><p>You can also render a block of code within a partial layout instead of calling <code>yield</code>. For example, if we didn't have the <code>_article</code> partial, we could do this instead:</p><p><strong>articles/show.html.erb</strong></p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
<% render(layout: 'box', locals: {article: @article}) do %>
<%= div_for(article) do %>
<p><%= article.body %></p>
<% end %>
<% end %>
</pre>
</div>
<p>Supposing we use the same <code>_box</code> partial from above, this would produce the same output as the previous example.</p><h3 id="view-paths">5 View Paths</h3><div class="todo"><p>..</p></div><h3 id="overview-of-helpers-provided-by-action-view">6 Overview of helpers provided by Action View</h3><p>WIP: Not all the helpers are listed here. For a full list see the <a href="http://api.rubyonrails.org/classes/ActionView/Helpers.html">API documentation</a></p><p>The following is only a brief overview summary of the helpers available in Action View. It's recommended that you review the <a href="http://api.rubyonrails.org/classes/ActionView/Helpers.html">API Documentation</a>, which covers all of the helpers in more detail, but this should serve as a good starting point.</p><h4 id="recordtaghelper">6.1 RecordTagHelper</h4><p>This module provides methods for generating container tags, such as <code>div</code>, for your record. This is the recommended way of creating a container for render your Active Record object, as it adds an appropriate class and id attributes to that container. You can then refer to those containers easily by following the convention, instead of having to think about which class or id attribute you should use.</p><h5 id="content-tag-for">6.1.1 content_tag_for</h5><p>Renders a container tag that relates to your Active Record Object.</p><p>For example, given <code>@article</code> is the object of <code>Article</code> class, you can do:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
<%= content_tag_for(:tr, @article) do %>
<td><%= @article.title %></td>
<% end %>
</pre>
</div>
<p>This will generate this HTML output:</p><div class="code_container">
<pre class="brush: xml; gutter: false; toolbar: false">
<tr id="article_1234" class="article">
<td>Hello World!</td>
</tr>
</pre>
</div>
<p>You can also supply HTML attributes as an additional option hash. For example:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
<%= content_tag_for(:tr, @article, class: "frontpage") do %>
<td><%= @article.title %></td>
<% end %>
</pre>
</div>
<p>Will generate this HTML output:</p><div class="code_container">
<pre class="brush: xml; gutter: false; toolbar: false">
<tr id="article_1234" class="article frontpage">
<td>Hello World!</td>
</tr>
</pre>
</div>
<p>You can pass a collection of Active Record objects. This method will loop through your objects and create a container for each of them. For example, given <code>@articles</code> is an array of two <code>Article</code> objects:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
<%= content_tag_for(:tr, @articles) do |article| %>
<td><%= article.title %></td>
<% end %>
</pre>
</div>
<p>Will generate this HTML output:</p><div class="code_container">
<pre class="brush: xml; gutter: false; toolbar: false">
<tr id="article_1234" class="article">
<td>Hello World!</td>
</tr>
<tr id="article_1235" class="article">
<td>Ruby on Rails Rocks!</td>
</tr>
</pre>
</div>
<h5 id="div-for">6.1.2 div_for</h5><p>This is actually a convenient method which calls <code>content_tag_for</code> internally with <code>:div</code> as the tag name. You can pass either an Active Record object or a collection of objects. For example:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
<%= div_for(@article, class: "frontpage") do %>
<td><%= @article.title %></td>
<% end %>
</pre>
</div>
<p>Will generate this HTML output:</p><div class="code_container">
<pre class="brush: xml; gutter: false; toolbar: false">
<div id="article_1234" class="article frontpage">
<td>Hello World!</td>
</div>
</pre>
</div>
<h4 id="assettaghelper">6.2 AssetTagHelper</h4><p>This module provides methods for generating HTML that links views to assets such as images, JavaScript files, stylesheets, and feeds.</p><p>By default, Rails links to these assets on the current host in the public folder, but you can direct Rails to link to assets from a dedicated assets server by setting <code>config.action_controller.asset_host</code> in the application configuration, typically in <code>config/environments/production.rb</code>. For example, let's say your asset host is <code>assets.example.com</code>:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
config.action_controller.asset_host = "assets.example.com"
image_tag("rails.png") # => <img src="http://assets.example.com/images/rails.png" alt="Rails" />
</pre>
</div>
<h5 id="register-javascript-expansion">6.2.1 register_javascript_expansion</h5><p>Register one or more JavaScript files to be included when symbol is passed to javascript_include_tag. This method is typically intended to be called from plugin initialization to register JavaScript files that the plugin installed in <code>vendor/assets/javascripts</code>.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
ActionView::Helpers::AssetTagHelper.register_javascript_expansion monkey: ["head", "body", "tail"]
javascript_include_tag :monkey # =>
<script src="/assets/head.js"></script>
<script src="/assets/body.js"></script>
<script src="/assets/tail.js"></script>
</pre>
</div>
<h5 id="register-stylesheet-expansion">6.2.2 register_stylesheet_expansion</h5><p>Register one or more stylesheet files to be included when symbol is passed to <code>stylesheet_link_tag</code>. This method is typically intended to be called from plugin initialization to register stylesheet files that the plugin installed in <code>vendor/assets/stylesheets</code>.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
ActionView::Helpers::AssetTagHelper.register_stylesheet_expansion monkey: ["head", "body", "tail"]
stylesheet_link_tag :monkey # =>
<link href="/assets/head.css" media="screen" rel="stylesheet" />
<link href="/assets/body.css" media="screen" rel="stylesheet" />
<link href="/assets/tail.css" media="screen" rel="stylesheet" />
</pre>
</div>
<h5 id="auto-discovery-link-tag">6.2.3 auto_discovery_link_tag</h5><p>Returns a link tag that browsers and feed readers can use to auto-detect an RSS or Atom feed.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
auto_discovery_link_tag(:rss, "http://www.example.com/feed.rss", {title: "RSS Feed"}) # =>
<link rel="alternate" type="application/rss+xml" title="RSS Feed" href="http://www.example.com/feed" />
</pre>
</div>
<h5 id="image-path">6.2.4 image_path</h5><p>Computes the path to an image asset in the <code>app/assets/images</code> directory. Full paths from the document root will be passed through. Used internally by <code>image_tag</code> to build the image path.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
image_path("edit.png") # => /assets/edit.png
</pre>
</div>
<p>Fingerprint will be added to the filename if config.assets.digest is set to true.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
image_path("edit.png") # => /assets/edit-2d1a2db63fc738690021fedb5a65b68e.png
</pre>
</div>
<h5 id="image-url">6.2.5 image_url</h5><p>Computes the url to an image asset in the <code>app/assets/images</code> directory. This will call <code>image_path</code> internally and merge with your current host or your asset host.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
image_url("edit.png") # => http://www.example.com/assets/edit.png
</pre>
</div>
<h5 id="image-tag">6.2.6 image_tag</h5><p>Returns an html image tag for the source. The source can be a full path or a file that exists in your <code>app/assets/images</code> directory.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
image_tag("icon.png") # => <img src="/assets/icon.png" alt="Icon" />
</pre>
</div>
<h5 id="javascript-include-tag">6.2.7 javascript_include_tag</h5><p>Returns an html script tag for each of the sources provided. You can pass in the filename (<code>.js</code> extension is optional) of JavaScript files that exist in your <code>app/assets/javascripts</code> directory for inclusion into the current page or you can pass the full path relative to your document root.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
javascript_include_tag "common" # => <script src="/assets/common.js"></script>
</pre>
</div>
<p>If the application does not use the asset pipeline, to include the jQuery JavaScript library in your application, pass <code>:defaults</code> as the source. When using <code>:defaults</code>, if an <code>application.js</code> file exists in your <code>app/assets/javascripts</code> directory, it will be included as well.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
javascript_include_tag :defaults
</pre>
</div>
<p>You can also include all JavaScript files in the <code>app/assets/javascripts</code> directory using <code>:all</code> as the source.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
javascript_include_tag :all
</pre>
</div>
<p>You can also cache multiple JavaScript files into one file, which requires less HTTP connections to download and can better be compressed by gzip (leading to faster transfers). Caching will only happen if <code>ActionController::Base.perform_caching</code> is set to true (which is the case by default for the Rails production environment, but not for the development environment).</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
javascript_include_tag :all, cache: true # =>
<script src="/javascripts/all.js"></script>
</pre>
</div>
<h5 id="javascript-path">6.2.8 javascript_path</h5><p>Computes the path to a JavaScript asset in the <code>app/assets/javascripts</code> directory. If the source filename has no extension, <code>.js</code> will be appended. Full paths from the document root will be passed through. Used internally by <code>javascript_include_tag</code> to build the script path.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
javascript_path "common" # => /assets/common.js
</pre>
</div>
<h5 id="javascript-url">6.2.9 javascript_url</h5><p>Computes the url to a JavaScript asset in the <code>app/assets/javascripts</code> directory. This will call <code>javascript_path</code> internally and merge with your current host or your asset host.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
javascript_url "common" # => http://www.example.com/assets/common.js
</pre>
</div>
<h5 id="stylesheet-link-tag">6.2.10 stylesheet_link_tag</h5><p>Returns a stylesheet link tag for the sources specified as arguments. If you don't specify an extension, <code>.css</code> will be appended automatically.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
stylesheet_link_tag "application" # => <link href="/assets/application.css" media="screen" rel="stylesheet" />
</pre>
</div>
<p>You can also include all styles in the stylesheet directory using :all as the source:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
stylesheet_link_tag :all
</pre>
</div>
<p>You can also cache multiple stylesheets into one file, which requires less HTTP connections and can better be compressed by gzip (leading to faster transfers). Caching will only happen if ActionController::Base.perform_caching is set to true (which is the case by default for the Rails production environment, but not for the development environment).</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
stylesheet_link_tag :all, cache: true
# => <link href="/assets/all.css" media="screen" rel="stylesheet" />
</pre>
</div>
<h5 id="stylesheet-path">6.2.11 stylesheet_path</h5><p>Computes the path to a stylesheet asset in the <code>app/assets/stylesheets</code> directory. If the source filename has no extension, .css will be appended. Full paths from the document root will be passed through. Used internally by stylesheet_link_tag to build the stylesheet path.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
stylesheet_path "application" # => /assets/application.css
</pre>
</div>
<h5 id="stylesheet-url">6.2.12 stylesheet_url</h5><p>Computes the url to a stylesheet asset in the <code>app/assets/stylesheets</code> directory. This will call <code>stylesheet_path</code> internally and merge with your current host or your asset host.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
stylesheet_url "application" # => http://www.example.com/assets/application.css
</pre>
</div>
<h4 id="atomfeedhelper">6.3 AtomFeedHelper</h4><h5 id="atom-feed">6.3.1 atom_feed</h5><p>This helper makes building an Atom feed easy. Here's a full usage example:</p><p><strong>config/routes.rb</strong></p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
resources :articles
</pre>
</div>
<p><strong>app/controllers/articles_controller.rb</strong></p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
def index
@articles = Article.all
respond_to do |format|
format.html
format.atom
end
end
</pre>
</div>
<p><strong>app/views/articles/index.atom.builder</strong></p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
atom_feed do |feed|
feed.title("Articles Index")
feed.updated((@articles.first.created_at))
@articles.each do |article|
feed.entry(article) do |entry|
entry.title(article.title)
entry.content(article.body, type: 'html')
entry.author do |author|
author.name(article.author_name)
end
end
end
end
</pre>
</div>
<h4 id="benchmarkhelper">6.4 BenchmarkHelper</h4><h5 id="benchmark">6.4.1 benchmark</h5><p>Allows you to measure the execution time of a block in a template and records the result to the log. Wrap this block around expensive operations or possible bottlenecks to get a time reading for the operation.</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
<% benchmark "Process data files" do %>
<%= expensive_files_operation %>
<% end %>
</pre>
</div>
<p>This would add something like "Process data files (0.34523)" to the log, which you can then use to compare timings when optimizing your code.</p><h4 id="cachehelper">6.5 CacheHelper</h4><h5 id="cache">6.5.1 cache</h5><p>A method for caching fragments of a view rather than an entire action or page. This technique is useful caching pieces like menus, lists of news topics, static HTML fragments, and so on. This method takes a block that contains the content you wish to cache. See <code>ActionController::Caching::Fragments</code> for more information.</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<% cache do %>
<%= render "shared/footer" %>
<% end %>
</pre>
</div>
<h4 id="capturehelper">6.6 CaptureHelper</h4><h5 id="capture">6.6.1 capture</h5><p>The <code>capture</code> method allows you to extract part of a template into a variable. You can then use this variable anywhere in your templates or layout.</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
<% @greeting = capture do %>
<p>Welcome! The date and time is <%= Time.now %></p>
<% end %>
</pre>
</div>
<p>The captured variable can then be used anywhere else.</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
<html>
<head>
<title>Welcome!</title>
</head>
<body>
<%= @greeting %>
</body>
</html>
</pre>
</div>
<h5 id="content-for">6.6.2 content_for</h5><p>Calling <code>content_for</code> stores a block of markup in an identifier for later use. You can make subsequent calls to the stored content in other templates or the layout by passing the identifier as an argument to <code>yield</code>.</p><p>For example, let's say we have a standard application layout, but also a special page that requires certain JavaScript that the rest of the site doesn't need. We can use <code>content_for</code> to include this JavaScript on our special page without fattening up the rest of the site.</p><p><strong>app/views/layouts/application.html.erb</strong></p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
<html>
<head>
<title>Welcome!</title>
<%= yield :special_script %>
</head>
<body>
<p>Welcome! The date and time is <%= Time.now %></p>
</body>
</html>
</pre>
</div>
<p><strong>app/views/articles/special.html.erb</strong></p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
<p>This is a special page.</p>
<% content_for :special_script do %>
<script>alert('Hello!')</script>
<% end %>
</pre>
</div>
<h4 id="datehelper">6.7 DateHelper</h4><h5 id="date-select">6.7.1 date_select</h5><p>Returns a set of select tags (one for year, month, and day) pre-selected for accessing a specified date-based attribute.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
date_select("article", "published_on")
</pre>
</div>
<h5 id="datetime-select">6.7.2 datetime_select</h5><p>Returns a set of select tags (one for year, month, day, hour, and minute) pre-selected for accessing a specified datetime-based attribute.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
datetime_select("article", "published_on")
</pre>
</div>
<h5 id="distance-of-time-in-words">6.7.3 distance_of_time_in_words</h5><p>Reports the approximate distance in time between two Time or Date objects or integers as seconds. Set <code>include_seconds</code> to true if you want more detailed approximations.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
distance_of_time_in_words(Time.now, Time.now + 15.seconds) # => less than a minute
distance_of_time_in_words(Time.now, Time.now + 15.seconds, include_seconds: true) # => less than 20 seconds
</pre>
</div>
<h5 id="select-date">6.7.4 select_date</h5><p>Returns a set of html select-tags (one for year, month, and day) pre-selected with the <code>date</code> provided.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# Generates a date select that defaults to the date provided (six days after today)
select_date(Time.today + 6.days)
# Generates a date select that defaults to today (no specified date)
select_date()
</pre>
</div>
<h5 id="select-datetime">6.7.5 select_datetime</h5><p>Returns a set of html select-tags (one for year, month, day, hour, and minute) pre-selected with the <code>datetime</code> provided.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# Generates a datetime select that defaults to the datetime provided (four days after today)
select_datetime(Time.now + 4.days)
# Generates a datetime select that defaults to today (no specified datetime)
select_datetime()
</pre>
</div>
<h5 id="select-day">6.7.6 select_day</h5><p>Returns a select tag with options for each of the days 1 through 31 with the current day selected.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# Generates a select field for days that defaults to the day for the date provided
select_day(Time.today + 2.days)
# Generates a select field for days that defaults to the number given
select_day(5)
</pre>
</div>
<h5 id="select-hour">6.7.7 select_hour</h5><p>Returns a select tag with options for each of the hours 0 through 23 with the current hour selected.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# Generates a select field for hours that defaults to the hours for the time provided
select_hour(Time.now + 6.hours)
</pre>
</div>
<h5 id="select-minute">6.7.8 select_minute</h5><p>Returns a select tag with options for each of the minutes 0 through 59 with the current minute selected.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# Generates a select field for minutes that defaults to the minutes for the time provided.
select_minute(Time.now + 6.hours)
</pre>
</div>
<h5 id="select-month">6.7.9 select_month</h5><p>Returns a select tag with options for each of the months January through December with the current month selected.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# Generates a select field for months that defaults to the current month
select_month(Date.today)
</pre>
</div>
<h5 id="select-second">6.7.10 select_second</h5><p>Returns a select tag with options for each of the seconds 0 through 59 with the current second selected.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# Generates a select field for seconds that defaults to the seconds for the time provided
select_second(Time.now + 16.minutes)
</pre>
</div>
<h5 id="select-time">6.7.11 select_time</h5><p>Returns a set of html select-tags (one for hour and minute).</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# Generates a time select that defaults to the time provided
select_time(Time.now)
</pre>
</div>
<h5 id="select-year">6.7.12 select_year</h5><p>Returns a select tag with options for each of the five years on each side of the current, which is selected. The five year radius can be changed using the <code>:start_year</code> and <code>:end_year</code> keys in the <code>options</code>.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# Generates a select field for five years on either side of Date.today that defaults to the current year
select_year(Date.today)
# Generates a select field from 1900 to 2009 that defaults to the current year
select_year(Date.today, start_year: 1900, end_year: 2009)
</pre>
</div>
<h5 id="time-ago-in-words">6.7.13 time_ago_in_words</h5><p>Like <code>distance_of_time_in_words</code>, but where <code>to_time</code> is fixed to <code>Time.now</code>.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
time_ago_in_words(3.minutes.from_now) # => 3 minutes
</pre>
</div>
<h5 id="time-select">6.7.14 time_select</h5><p>Returns a set of select tags (one for hour, minute and optionally second) pre-selected for accessing a specified time-based attribute. The selects are prepared for multi-parameter assignment to an Active Record object.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# Creates a time select tag that, when POSTed, will be stored in the order variable in the submitted attribute
time_select("order", "submitted")
</pre>
</div>
<h4 id="debughelper">6.8 DebugHelper</h4><p>Returns a <code>pre</code> tag that has object dumped by YAML. This creates a very readable way to inspect an object.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
my_hash = {'first' => 1, 'second' => 'two', 'third' => [1,2,3]}
debug(my_hash)
</pre>
</div>
<div class="code_container">
<pre class="brush: xml; gutter: false; toolbar: false">
<pre class='debug_dump'>---
first: 1
second: two
third:
- 1
- 2
- 3
</pre>
</pre>
</div>
<h4 id="formhelper">6.9 FormHelper</h4><p>Form helpers are designed to make working with models much easier compared to using just standard HTML elements by providing a set of methods for creating forms based on your models. This helper generates the HTML for forms, providing a method for each sort of input (e.g., text, password, select, and so on). When the form is submitted (i.e., when the user hits the submit button or form.submit is called via JavaScript), the form inputs will be bundled into the params object and passed back to the controller.</p><p>There are two types of form helpers: those that specifically work with model attributes and those that don't. This helper deals with those that work with model attributes; to see an example of form helpers that don't work with model attributes, check the ActionView::Helpers::FormTagHelper documentation.</p><p>The core method of this helper, form_for, gives you the ability to create a form for a model instance; for example, let's say that you have a model Person and want to create a new instance of it:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
# Note: a @person variable will have been created in the controller (e.g. @person = Person.new)
<%= form_for @person, url: {action: "create"} do |f| %>
<%= f.text_field :first_name %>
<%= f.text_field :last_name %>
<%= submit_tag 'Create' %>
<% end %>
</pre>
</div>
<p>The HTML generated for this would be:</p><div class="code_container">
<pre class="brush: xml; gutter: false; toolbar: false">
<form action="/people/create" method="post">
<input id="person_first_name" name="person[first_name]" type="text" />
<input id="person_last_name" name="person[last_name]" type="text" />
<input name="commit" type="submit" value="Create" />
</form>
</pre>
</div>
<p>The params object created when this form is submitted would look like:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
{"action" => "create", "controller" => "people", "person" => {"first_name" => "William", "last_name" => "Smith"}}
</pre>
</div>
<p>The params hash has a nested person value, which can therefore be accessed with params[:person] in the controller.</p><h5 id="check-box">6.9.1 check_box</h5><p>Returns a checkbox tag tailored for accessing a specified attribute.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# Let's say that @article.validated? is 1:
check_box("article", "validated")
# => <input type="checkbox" id="article_validated" name="article[validated]" value="1" />
# <input name="article[validated]" type="hidden" value="0" />
</pre>
</div>
<h5 id="fields-for">6.9.2 fields_for</h5><p>Creates a scope around a specific model object like form_for, but doesn't create the form tags themselves. This makes fields_for suitable for specifying additional model objects in the same form:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
<%= form_for @person, url: {action: "update"} do |person_form| %>
First name: <%= person_form.text_field :first_name %>
Last name : <%= person_form.text_field :last_name %>
<%= fields_for @person.permission do |permission_fields| %>
Admin? : <%= permission_fields.check_box :admin %>
<% end %>
<% end %>
</pre>
</div>
<h5 id="file-field">6.9.3 file_field</h5><p>Returns a file upload input tag tailored for accessing a specified attribute.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
file_field(:user, :avatar)
# => <input type="file" id="user_avatar" name="user[avatar]" />
</pre>
</div>
<h5 id="form-for">6.9.4 form_for</h5><p>Creates a form and a scope around a specific model object that is used as a base for questioning about values for the fields.</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
<%= form_for @article do |f| %>
<%= f.label :title, 'Title' %>:
<%= f.text_field :title %><br>
<%= f.label :body, 'Body' %>:
<%= f.text_area :body %><br>
<% end %>
</pre>
</div>
<h5 id="hidden-field">6.9.5 hidden_field</h5><p>Returns a hidden input tag tailored for accessing a specified attribute.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
hidden_field(:user, :token)
# => <input type="hidden" id="user_token" name="user[token]" value="#{@user.token}" />
</pre>
</div>
<h5 id="label">6.9.6 label</h5><p>Returns a label tag tailored for labelling an input field for a specified attribute.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
label(:article, :title)
# => <label for="article_title">Title</label>
</pre>
</div>
<h5 id="password-field">6.9.7 password_field</h5><p>Returns an input tag of the "password" type tailored for accessing a specified attribute.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
password_field(:login, :pass)
# => <input type="text" id="login_pass" name="login[pass]" value="#{@login.pass}" />
</pre>
</div>
<h5 id="radio-button">6.9.8 radio_button</h5><p>Returns a radio button tag for accessing a specified attribute.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# Let's say that @article.category returns "rails":
radio_button("article", "category", "rails")
radio_button("article", "category", "java")