動態更新資訊饋送中的項目
簡介
此範例示範如何顯示資料饋送,讓使用者無需捲動即可瀏覽電子郵件中的大量項目。
此範例結合使用 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
,該 amp-form
參考上述透過其 id
定義的範本。透過為 amp-form
使用不同的範本,我們可以「重新整理」部分內容,在此案例中為圖片。
此範本包含與上述範本中用於呈現初始項目相同的標記 (在此案例中為單一
amp-img
)。這會包裝在 <div class="initial-content">
中,該標記在使用者首次提交表單時會變成隱藏。<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