if custom field (zh-tw)
From Textbook
Contents |
類型
if_custom_field 為 條件式標籤,因為所有的條件式標籤皆為圍堵標籤,所以此標籤也是 圍堵標籤。這個標籤會檢查文章自訂欄位是否有設定內容,如果有的話,就輸出相關代碼。(自訂欄位內容的顯示使用 <txp:custom_field /> 標籤)
語法
if_custom_field 標籤的語法結構如下...
<txp:if_custom_field> ...有內容的話顯示這些代碼... <txp:else /> ...沒有的話顯示這些代碼... </txp:if_custom_field>
屬性
此標籤接受下列的屬性 (註:屬性區分 大小寫):
- name="add name here" (只檢查特定的自訂欄位名稱。)
- val="add content here" (檢查自訂欄位的內容是否等同此設定值)
範例
範例 1: 顯示自訂欄位的內容
關於如何顯示自訂欄位內容在 <txp:custom_field /> 標籤說明頁 裡有介紹。
範例 2: 顯示自訂欄位內容,但無內容時不顯示任何東西
自訂欄位條件式標籤的作用是檢查自訂欄位是否有內容,如果有的話,就輸出標籤之內的代碼。更進階的使用方法是檢查自訂欄位是否有特定的內容,但我們在範例 3 裡才會提到它。現在先介紹基本自訂欄位條件式標籤的使用方式。
假設,你在你的網站已發表了書籍評論,而且作者(Author)、書名(Title)、出版社(Publisher)、發行年度(Year) 這些出版資訊的自訂欄位都已輸入相關資料 (請見範例)。
只是一些書籍有副標題,其他沒有。你可以利用 if_custom_field 檢查是否有副標題。藉由在條件式裡指定 name 屬性為 "subtitle";這樣如果書籍有副標題的話,就會顯示副標題,若沒有的話則不會在頁面上顯示此欄位。部份代碼如下:
<txp:if_custom_field name="subtitle"> <txp:custom_field name="subtitle" /> </txp:if_custom_field>
若自訂欄位內容為空,將不顯示任何東西。
全部代碼如下:
<p><txp:custom_field name="author" />: <txp:custom_field name="title" /> <br />
<txp:if_custom_field name="subtitle">
<txp:custom_field name="subtitle" /><br />
</txp:if_custom_field>
published by <txp:custom_field name="publisher" /> in <txp:custom_field name="year" />.</p>
書籍有副標題 的情況下,會輸出:
<p>Stephen Covey: The Seven Habits of Highly Effective People<br /> Powerful Lessons in Personal Change <br /> published by Simon & Schuster in 2002.</p>
書籍沒有副標題 的情況下,會輸出:
<p>J.R.R. Tolkien: The Lord of the Rings <br /> published by HarperCollins in 2004.</p>
範例 3: 當自訂欄位內容等同於指定的值時才顯示
一個很有趣的運用方式是心情圖示。假設,你定義一個名為 "mood" 的自訂欄位,用以輸入發表文章時的心情。輸入的內容是 "happy" 或 "sad"。
在文章裡,你想要使用表情符號分別代表這些心情。文章模型內的代碼可以像這樣:
... <txp:if_custom_field name="mood" val="happy"> <img src="/images/happy-face.gif" alt="" /> </txp:if_custom_field> <txp:if_custom_field name="mood" val="sad"> <img src="/images/sad-face.gif" alt="" /> </txp:if_custom_field> ...
範例 4: 顯示自訂欄位內容,若無內容就顯示一些其他資訊
假設你已發表過音樂評論,而且也設定了樂團名稱、專輯名稱、樂團網站這些自訂欄位。但並不是每個樂團都有網站,你或許會想在當樂團沒有網站時顯示一些基本訊息。
代碼可以像這樣:
... <txp:if_custom_field name="website"> <txp:custom_field name="website" /> <txp:else /> <p>很遺憾!這樂團沒有網站。</p> </txp:if_custom_field> ...




