AMP
  • 電子郵件

動態更新 Feed 中的項目

簡介

這個範例示範如何在電子郵件中顯示資料 Feed,讓使用者瀏覽大量項目而無需捲動。

這個範例結合了 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"> 內,該元素會在使用者首次提交表單時隱藏。

<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 上編輯範例