AMP
  • 網站

amp-mustache

簡介

amp-mustache 範本是一個基於 mustache 的簡單結構化範本系統。

amp-mustache 實際上不提供資料,也不編譯範本。相反地,資料是由其他 AMP 標籤(例如 amp-accessamp-formamp-list)提供和編譯範本。如需這些使用案例的更多資訊,請直接參閱這些文件/範例。

設定

匯入 amp-mustache 標籤。

<script async custom-template="amp-mustache" src="https://cdn.ampproject.org/v0/amp-mustache-0.2.js"></script>

amp-mustache 需要與其他元件一起使用,例如 amp-listamp-form。為了此範例的目的,我們將使用 amp-list

<script async custom-element="amp-list" src="https://cdn.ampproject.org/v0/amp-list-0.1.js"></script>

amp-mustache 範本的資料由其他 AMP 標籤提供。為了此示範的目的,我們使用 amp-list 傳入 JSON 檔案,其中包含如下的字典

{
  "items": [
    {
      "fullname": "John Doe",
      "phonenumber": "212-555-1212",
      "cart_items": [
        {
          "name": "Pluot",
          "quantity": 5,
          "price": "$1.00"
        },
        {
          "name": "Apple",
          "quantity": 1,
          "price": "$3.25"
        }
      ],
      "address": {
        "addr1": "111 8th Ave",
        "city": "New York",
        "state": "NY",
        "zipcode": 10011
      }
    }
  ]
}

變數

當變數名稱以雙重花括號 ({{varname}}) 包圍時,變數會被內插。

<amp-list src="/static/samples/json/cart.json" layout="fixed-height" height="56" binding="no">
  <template type="amp-mustache">
    Hi {{fullname}}!
  </template>
</amp-list>

條件式

條件式使用相同的語法呼叫,但在前面加上井字號 (#)。

<amp-list src="/static/samples/json/cart.json" layout="fixed-height" height="56" binding="no">
  <template type="amp-mustache">
    {{#phonenumber}}
      The registered phone number is {{phonenumber}}
    {{/phonenumber}}
  </template>
</amp-list>

負條件式

對於負條件式,請在變數名稱前插入插入符號 (^)。

<amp-list src="/static/samples/json/cart.json" layout="fixed-height" height="56" binding="no">
  <template type="amp-mustache">
    {{^twitter}}
      There is no registered twitter account for this profile
    {{/twitter}}
  </template>
</amp-list>

迴圈

迴圈使用與條件式相同的語法,但當提供列表而不是純量變數(例如字串、整數和字典)時,迴圈會運作。

<amp-list src="/static/samples/json/cart.json" layout="fixed-height" height="80" binding="no">
  <template type="amp-mustache">
    <div id="cart">
      {{#cart_items}}
      <div class="cart-item">
        <span>{{name}}</span>
        <span>{{quantity}}</span>
        <span>{{price}}</span>
      </div>
      {{/cart_items}}
      {{^cart_items}}
      <div>Your cart is empty!</div>
      {{/cart_items}}
    </div>
  </template>
</amp-list>
需要進一步說明嗎?

如果此頁面上的說明沒有涵蓋您的所有問題,請隨時聯繫其他 AMP 使用者,討論您的確切使用案例。

前往 Stack Overflow
未說明的特色功能?

AMP 專案強烈鼓勵您的參與和貢獻!我們希望您能成為我們開放原始碼社群的持續參與者,但我們也歡迎針對您特別感興趣的問題提供一次性貢獻。

在 GitHub 上編輯範例