Today, with the increasing richness of website content, how to enable users to quickly find the information they are interested in is a crucial operational issue.AnQiCMS (AnQiCMS) provides powerful content management capabilities, and its API interface provides a solid foundation for front-end developers to build flexible and variable interactive interfaces.Today, let's delve into how to make use ofarchiveFiltersThe response data of the interface, dynamically constructing the front-end filtering UI, such as common dropdown menus or checkboxes.

The value of the dynamic filtering interface

Imagine if your website has a large number of products, articles, or job listings, users may want to filter based on various conditions such as 'price range', 'publish time', 'city', 'education', and more.If these filter conditions are fixed, each adjustment on the backend will require front-end engineers to modify the code, which undoubtedly increases the maintenance cost.By dynamically building the filtering UI, the front-end can automatically generate the corresponding drop-down menus or checkboxes based on the real-time filtering conditions returned by the back-end interface, greatly enhancing the flexibility and maintainability of the website.

RevelationarchiveFiltersInterface: data source for filtering conditions

Of Security CMSarchiveFiltersThe interface is the core to implement this function. It allows us to get the list of filtering conditions for the specified content model.

Calling this interface is very simple, just need to send{域名地址}/api/archive/filtersSend aGETRequest and include a required parametermoduleId,moduleIdIndicates the filtering conditions under which content model you want to retrieve (such as article model, product model, etc.)

The response data structure of the interface is clear and straightforward, it usually returns an array containing multiple filter objects. Each filter object contains several key pieces of information:

  • name: This is the Chinese name that should be used for the filter on the front end, such as "City", "Education", etc., which users will see directly.
  • field_name: This is the backend field name corresponding to the filter, for examplecity/certificate. This name is very important because when the user selects the filter condition, we will transfer thisfield_nameAs a parameter name, send it together with the user's chosen valuearchiveListto get the document list that meets the conditions.
  • items: This is an array that includes all the available options of the current filter. Each option also includeslabel(The actual display text of the option, such as “Beijing”, “Bachelor”) andtotalThis indicates how many documents are under this option, although it is displayed as 0 in the example, but it can be used in actual projects according to need to display the number.

By parsing this response, we can know which filtering dimensions the current content model supports, and what specific options each dimension has.

{
  "code": 0,
  "data": [
    {
      "name": "城市",
      "field_name": "city",
      "items": [
        { "label": "全部", "total": 0 },
        { "label": "北京", "total": 0 },
        { "label": "上海", "total": 0 }
      ]
    },
    {
      "name": "学历",
      "field_name": "certificate",
      "items": [
        { "label": "全部", "total": 0 },
        { "label": "硕士", "total": 0 },
        { "label": "本科", "total": 0 }
      ]
    }
  ],
  "msg": ""
}

Practical steps for dynamically building the front-end UI.

NowarchiveFiltersThe powerful data provided, next is how to convert this data into a user-friendly filter interface on the front end.

Step 1: Obtain the filter data

Firstly, when the page loads or when the user switches the content model, we need to callarchiveFiltersThe interface retrieves the latest filtering conditions. This is usually an asynchronous operation, which can be done using JavaScript'sfetchoraxioslibraries.

async function fetchFilters(moduleId) {
  try {
    const response = await fetch(`/api/archive/filters?moduleId=${moduleId}`);
    const result = await response.json();
    if (result.code === 0) {
      return result.data; // 返回筛选器数据数组
    } else {
      console.error('获取筛选条件失败:', result.msg);
      return [];
    }
  } catch (error) {
    console.error('请求筛选条件接口出错:', error);
    return [];
  }
}

Step two: Parse and render UI components

obtaining todataAfter the array, we can iterate over this array to dynamically create front-end UI elements for each filter. For each filter object, we can use itsnameUse as the title of the filter area,field_nameWill be used as the parameter name of the backend request,itemsThe array is used to generate specific options.

Here, we can decide based on actual needs whether to use a dropdown menu (<select>) or a checkbox (<input type="checkbox">)

Create a dropdown menu (suitable for single selection filters, such as "City"):

If a user typically only selects one value for a filter dimension (such as "city"), a dropdown menu is a simple and effective choice.

function renderDropdownFilter(filterData) {
  const filterContainer = document.getElementById('filters-area'); // 假设页面上有一个ID为'filters-area'的容器
  const div = document.createElement('div');
  div.className = 'filter-group';

  const label = document.createElement('label');
  label.textContent = filterData.name + ':';
  div.appendChild(label);

  const select = document.createElement('select');
  select.setAttribute('data-field-name', filterData.field_name); // 存储field_name,方便后续获取选中的值

  filterData.items.forEach(item => {
    const option = document.createElement('option');
    option.value = item.label === '全部' ? '' : item.label; // 如果是“全部”选项,值可以设置为空字符串
    option.textContent = item.label;
    select.appendChild(option);
  });

  select.addEventListener('change', (event) => {
    // 处理用户选择的变化,触发文档列表更新
    // 例如:updateArchiveList(filterData.field_name, event.target.value);
    console.log(`选中 ${filterData.name}: ${event.target.value}`);
  });

  div.appendChild(select);
  filterContainer.appendChild(div);
}

Create a checkbox group (for multi-select filtering, such as “Tags” or certain custom attributes):

If a user may need to select multiple values for a filter dimension (such as filtering multiple 'specialties'), a group of checkboxes would be more appropriate.

`javascript function renderCheckboxFilter(filterData) { const filterContainer = document.getElementById('filters-area'); const div = document.createElement(‘div’); div.className = 'filter-group';

const label = document.createElement(‘label’); label.textContent = filterData.name + ":"; div.appendChild(label);

const checkboxGroup = document.createElement('div'); checkboxGroup.className = 'checkbox-options';

filterData.items.forEach(item => {

// 排除“全部”选项,多选框通常不需要