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