AMP
  • websites

Client-side filtering

Introduction

This is a sample showing how to implement client-side filtering.

Setup

Additionally used AMP components must be imported in the header. We use amp-bind to store products locally into a variable.

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

We use amp-list to retrieve static data.

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

We use amp-mustache to render data.

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

Client-side Filter

It is possible to implement client-side filtering by using amp-list, amp-state and amp-bind.

The amp-state is initially setup with data from an endpoint which returns a list of available products; the user can choose between different colors and that selection sets the variable filteredProducts to the result of a filter expression. The filter expression is an amp-bind expression which uses the Array.filter function.

The filteredProducts variable is then used as src of amp-list. amp-list does not resize automatically, but it is possible to calculate its height in the filtered state by using amp-bind: here we are binding the [height] to the length of the filteredProducts array times the height of a single element.

The alternative to this approach is using server-side filtering which we explain in the product sample.

<amp-state id="allProducts" src="/static/samples/json/related_products.json"></amp-state>
<select on="change:AMP.setState({
    filteredProducts: allProducts.items.filter(a => event.value == 'all' ? true : a.color == event.value)
  })">
  <option value="all" selected>All</option>
  <option value="red">red</option>
  <option value="green">green</option>
  <option value="yellow">yellow</option>
  <option value="orange">orange</option>
</select>
<amp-list height="282" [height]="(40 + 24) * filteredProducts.length" layout="fixed-height" src="/static/samples/json/related_products.json" [src]="filteredProducts" binding="no">
  <template type="amp-mustache">
    <amp-img src="{{img}}" layout="fixed" width="60" height="40" alt="{{name}}"></amp-img>
    {{name}}
  </template>
</amp-list>
هل تحتاج إلى مزيد من التوضيح؟

إذا لم تكن الإيضاحات الموجودة في هذه الصفحة تُجيب على جميع أسئلتك، فلا تتردد في التواصل مع مستخدمي AMP الآخرين لمناقشة حالة الاستخدام المحددة لديك بالضبط.

الذهاب إلى Stack Overflow
هل هي ميزة غير موضحة؟

يشجع مشروع AMP مشاركتك ومساهمتك بشدة! ونأمل أن تكون مشاركًا دائمًا في مجتمعنا مفتوح المصدر، ولكننا نشجع أيضًا المساهمات التي تحدث لمرة واحدة في الأمور التي تتحمس لها.

تعديل العينة على GitHub