apostrophe-cms - 使用 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.html
,indexAjax.html
甚至indexCustom.html
使用类似于上面 Nunjucks 示例的自定义。我知道如何做游标并通过它来操作数据。我学得很慢,但我从不停止学习。先感谢您。
P/s:如果你们可以在 HOWTO 部分为这个“额外的渲染/覆盖数据到页面”发布一个新教程,那将非常有帮助!
解决方案
要为您的页面模板提供更多数据,最简单的方法是监听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
方法,但这会迫使您使用回调,而 Promise 绝对是 2018 年的发展方向。
您没有详细说明您的用例,所以我的示例是一种以通常方式扩展片段的方法,但确保所有片段在每个页面上都可用 - 这可能是一个好主意,也可能是一个糟糕的主意,取决于你有多少,但它展示了这项技术。
推荐阅读
- bash - JQ 选择和传递参数
- regex - POSIX 正则表达式中的环视以匹配除最后一个之外的所有空格(对于 gsub)
- c# - 返回元组时将 foreach 转换为变量分配
- reactjs - 填充所有值后如何自动调用函数
- java - Maven没有下载依赖项
- php - PHP 7.4.1 - PECL 不工作(尝试访问第 181 行 PEAR/REST.php 中 bool 类型值的数组偏移量)
- amazon-redshift - 如何计算红移中的MTD
- python - 打开文件从文件中删除行
- excel - 避免在excel的列中粘贴重复的一组值
- vim - 检测缓冲区是否在状态行的非活动窗口中