iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 9
0
Modern Web

Rails guide / Ruby API study系列 第 9

[ Rails guide study ] Day09 yield & content_for的使用 (Layouts and Rendering in Rails part3)

首先來聽首歌吧
Yes
椎名林檎是一個我見過曲風最多變的創作歌手,這首是我認為數一數二好聽的歌!雖然這個樂團已經解散,但他本人還是有持續在創作,請大家多多支持!


今天從第三章繼續看下去,這裡講到 layout 的使用方法

有三個工具,可以幫助 layout 更完整

  1. Asset tags
  2. yield and content_for
  3. Partials

Asset tags

這方面的應用在文章中的範例已經很完整了,比較常用的有下面這些 tag,有需要的翻一下使用手冊囉!

auto_discovery_link_tag
javascript_include_tag
stylesheet_link_tag
image_tag
video_tag
audio_tag


Yield and content_for

之前已經有稍微提到過 yield 這個東西,他會把 layout 這部分的內容 "讓" 給 views 資料夾中對應的 controller_name#action_name 檔案,今天再多說些 layout 的用法

在 layout 中可以 yield 不只一次,只是如果這樣做的話,必須指定這個 yield 的內容
比方說我在 layout 中像下面這樣寫

<!--application.html.erb-->

<!DOCTYPE html>
<html>
  <head>
    <%= yield :head %>
  </head>

  <body>
    <%= yield %>
  </body>
</html>

上面的 yield :head 表示我讓給 head 這邊表示這裏的內容,然後我在對應的檔案也要標示他的範圍在哪裡

<!-- index.html.erb-->
<% content_for :head do %>
<title>Who's your daddy</title>
<% end %>
<p>No, I'm mommy</p>

我在 index.html.erb 檔案中也要使用 content_for 方法寫出呼應的 :head 是從哪裡到哪裡
在這之外的部分就是正常的 yield 會跑出來的部分
出現的結果會在下面


從圖片可以看到網頁的 title 被我使用 yield 的方法換掉了!
而本文中的字是一開始的 yield 所讓出來的內容

明天開始會介紹 partial 的用法,請敬請期待!

參考資料
Rails Guide

本文章同步分享於 http://anthonychao.site/


上一篇
[ Rails guide study ] Day08 Layout 的基本使用 (Layouts and Rendering in Rails part2)
下一篇
[ Rails guide study ] Day10 partial 的使用
系列文
Rails guide / Ruby API study30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言