首页 > 解决方案 > 使用 ApostropheCMS 语言渲染页面

问题描述

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

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

我在本文档中找到了您的撇号文档,该文档使用render(req, name, data). 我想自定义我的光标并像上面使用 nunjucks 一样覆盖。 req.data我发现是正确的使用方法,我不知道从哪里开始!我应该使用self.beforeShow吗?我不想self.route在发生 GET 请求的地方使用。我只想添加额外的数据并将其呈现在上面show.htmlindexAjax.html甚至indexCustom.html使用类似于上面 Nunjucks 示例的自定义。我知道如何做游标并通过它来操作数据。我学得很慢,但我从不停止学习。先感谢您。

P/s:如果你们可以在 HOWTO 部分为这个“额外的渲染/覆盖数据到页面”发布一个新教程,那将非常有帮助!

标签: apostrophe-cms

解决方案


要为您的页面模板提供更多数据,最简单的方法是监听apostrophe-pages:beforeSendpromise 事件(使用 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方法,但这会迫使您使用回调,而 Promise 绝对是 2018 年的发展方向。

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


推荐阅读