使用 ApostropheCMS 语言渲染页面

Render Page using ApostropheCMS Language

我知道要问这种愚蠢的问题。但是对于初学者和熟悉 express nodejs 的人来说,这个问题也可能对其他人有用。对我来说,我熟悉通过使用 express nodejs 使用这种方法渲染 nunjucks。这是一个我们都知道的例子:

nunjucks.render('index.html', { foo: 'bar' });

我发现你的撇号文档 documentation that using render(req, name, data) . I want to customize my cursor and override req.data like using nunjucks above . And I found out that this 是正确的使用方法,我不知道从哪里开始!我应该使用 self.beforeShow 吗?我不想在发生 GET 请求的地方使用 self.route。我只想添加额外的数据并将其呈现在 show.htmlindexAjax.html 上,甚至使用与上面的 Nunjucks 示例类似的自定义 indexCustom.html 。我知道如何做游标并通过它来操作数据。我学得慢,但我从不停止学习。先感谢您。

P/s : If you guys can post a new tutorial at HOWTO section for this "extra rendering/override data into the page" , that would be extremely helpful !

要使其他数据可用于您的页面模板,最简单的方法是侦听 apostrophe-pages:beforeSend promise 事件(使用 Apostrophe 2.63.0 或更新版本):

// in app.js

var apos = require('apostrophe')({
  shortName: 'myproject',
  // among other things
  modules: {
    'apostrophe-pieces': {}
  }
});

// in lib/modules/products/index.js


module.exports = {
  extend: 'apostrophe-pieces',
  name: 'product',
  construct: function(self, options) {
    self.on('apostrophe-pages:beforeSend', 'getAllProducts', function(req) {
      // Let's assume you have a "products" module that extends pieces
      // and you want all of them on every page (not necessarily a good idea)
      return self.apos.modules.products.find(req).toArray().then(function(products) {
        req.data.products = products;
      });
    });
  }  
};

{# In any page template or layout #}

{% for product in data.products %}
  {{ product.title }}
{% endfor %}

较早的方法是实现 pageBeforeSend 方法,但这会迫使您使用回调,而 promises 绝对是 2018 年的发展方向。

您没有详细说明您的用例,所以我这里的示例是一种以通常方式扩展片段的方法,但要确保所有片段在每个页面上都可用 - 这可能是个好主意或一个糟糕的,取决于你有多少,但它展示了技术。