6

什麼時機要用 Helper, 什麼時機要用 partial

 2 years ago
source link: https://blog.niclin.tw/2015/12/09/%E4%BB%80%E9%BA%BC%E6%99%82%E6%A9%9F%E8%A6%81%E7%94%A8-helper-%E4%BB%80%E9%BA%BC%E6%99%82%E6%A9%9F%E8%A6%81%E7%94%A8-partial/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Helper:

使用 Helper 的情境多半是:

  • 產生的 HTML code 需要與原始程式碼進行一些邏輯混合,但不希望 View 裡面搞得太髒。
  • 需要與預設的 Rails 內建的一些方便 Helper 交叉使用。

使用 Helper 封裝程式碼可以帶給專案以下一些優點:

  • Don’t repeat yourself(DRY)程式碼不重複
  • Good Encapsulation好的封裝性
  • 提供 view 模板良好的組織
  • 易於修改程式碼

partial:

Partial 簡單說就是程式碼中的一小段,通常使用在 HTML 中讓 View的Code 可以更乾淨,將重複使用到的區塊切成獨立的 Partial,比方說頁首頁尾、表單、社群插件等等,讓任何一個頁面都可以讀取這段Partial而不用重複寫一次一模一樣的Code。

使用 的情境是:

  • long template | 如果當檔 HTML 超過兩頁
  • highly duplicated | HTML 內容高度重複
  • independent blocks | 可獨立作為功能區塊

什麼時機使用:

partial 負責處理大片的 HTML code,或是之後要利用 ajax render 出來的片段。

helper 則負責處理跟邏輯判斷有關的東西。


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK