動態更新資訊饋送中的項目
簡介
此範例示範如何顯示資料饋送,讓使用者瀏覽電子郵件中的大量項目,而無需捲動。
此範例結合使用 amp-list
(從伺服器擷取初始項目) 和 amp-form
(透過發出新的伺服器要求來「重新整理」單一項目)。
樣式
我們使用 CSS 在首次提交表單後隱藏最初擷取的項目。
我們也定義了版面配置,讓我們可以擁有固定的卡片大小,以確保提交表單不會導致內容跳動。
<style amp-custom>
.amp-form-submit-success .initial-content,
.amp-form-submitting .initial-content,
.amp-form-submit-error .initial-content {
display: none;
}
.card {
width: 160px;
height: 120px;
margin: 10px;
float: left;
position: relative;
}
.card .next-button {
position: absolute;
bottom: 0;
width: 100%;
}
</style>
單一項目範本
在卡片內定義單一項目的範本,並給予 id
。此範本由 amp-form
用於顯示新項目。
在此範例中,我們使用單一 amp-img
。
<template id="item-template" type="amp-mustache">
<amp-img src="{{items.imageUrl}}" layout="fixed" width="160" height="90"></amp-img>
</template>
初始項目清單
我們定義初始項目及其版面配置的範本,並給予 id
,讓我們隨後可以在 amp-list 中使用它。此範本由 amp-list
用於從伺服器擷取最新的初始內容。
它本身包含每個項目的 amp-form
,該表單參考由其 id
參照的上述範本。透過為 amp-form
使用不同的範本,我們可以「重新整理」部分內容,即此範例中的圖片。
此範本包含與上述範本中用於呈現初始項目的標記 (在此範例中為單一
amp-img
) 相同的標記。這會包裝在 <div class="initial-content">
中,該 div 在使用者首次提交表單時會變成隱藏。<template id="list-template" type="amp-mustache">
<form class="card" method="post" action-xhr="https://amp.dev.org.tw/documentation/examples/api/photo-stream?single&width=160&height=90">
<div class="initial-content">
<amp-img src="{{imageUrl}}" layout="fixed" width="160" height="90"></amp-img>
</div>
<div submit-success template="item-template"></div>
<input class="next-button" type="submit" value="Next">
</form>
</template>
我們使用 amp-list
從伺服器使用由其 id
參照的上述範本來呈現初始項目。
高度符合我們的卡片及其邊界組合高度。初始伺服器回應定義要顯示的卡片數量 (在此範例中為四張)。
<amp-list template="list-template" src="https://amp.dev.org.tw/documentation/examples/api/photo-stream?width=160&height=90&items=4" layout="fixed" width="360" height="280">
</amp-list>
需要更多說明嗎?
如果此頁面上的說明未涵蓋您的所有問題,請隨時聯絡其他 AMP 使用者,討論您的確切使用案例。
前往 Stack Overflow 不明原因的功能?AMP 專案強烈鼓勵您的參與和貢獻!我們希望您能成為我們開放原始碼社群的長期參與者,但我們也歡迎您針對您特別感興趣的問題做出一次性貢獻。
在 GitHub 上編輯範例-
作者: @fstanis