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