创建一个小部件以列出具有自定义属性的页面

Creating a widget to list pages with a custom attribute

这是我第一次尝试使用撇号创建网站,请见谅!

我在类似于以下内容的页面上创建了一个自定义属性:

module.exports = {
  beforeConstruct: function(self, options) {
    options.addFields = [
      {
        name: 'include_in_list', 
        label: 'Include In List',
        type: 'boolean'
      }
    ].concat(options.addFields || []);    
  }
};

现在的目标是创建一个小部件,显示所有设置了此标志的页面的链接,但我正在努力弄清楚下一步该去哪里...如何列出设置了标志的页面和然后将该列表公开到我的小部件的模板?

  1. 最直接(且更手动)的方法是将 joinByArray 字段添加到以页面为目标的小部件,然后手动将您的页面加入到小部件。这将使您可以使用 UI 对连接页面的顺序进行排序,但必须手动更新才能向小部件添加更多页面。 https://apostrophecms.org/docs/tutorials/getting-started/schema-guide.html#code-join-by-array-code

  1. 一种更像您描述的方式(但更不透明)是覆盖小部件的 load 方法并在页面加载时手动获取目标页面。

/lib/modules/special-widgets/index.js

module.exports = {
  extend: 'apostrophe-widgets',
  label: 'Special',
  construct: function (self, options) {
    const superLoad = self.load;
    self.load = function (req, widgets, callback) {
      return superLoad(req, widgets, function (err) {
        if (err) {
          return callback(err);
        }
        // `widgets` is each widget of this type being loaded on a page
        return self.apos.modules['apostrophe-pages'].find(req, { mySpecialProp: true }, {slug: 1, type: 1, _id: 1, title: 1}).toArray(function (err, docs) {
          widgets.forEach(function (widget) {
            // attach docs to each widget, in your widget template this becomes data.widget._pages
            widget._pages = docs;
          });
          return callback(null);
        })        
      });
    };
  }
}

在您的 lib/modules/special-widgets/views/widget.html 中,您可以在 data.widget._pages

中访问此页面数组

请注意 { mySpecialProp: true } 是您查找的条件对象,将其设置为查找您的页面 属性。

Working with Cursors

阅读有关 .find() 方法的更多信息