【问题标题】:Render Page using ApostropheCMS Language使用 ApostropheCMS 语言渲染页面
【发布时间】:2018-08-18 05:41:42
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: apostrophe-cms


    【解决方案1】:

    要为您的页面模板提供更多数据,最简单的方法是监听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 年的发展方向。

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

    【讨论】:

    • 请问。 self.on 上可用的论点是什么?第一个参数是调用 apostrophe-pages 模块,在 ":" 之后是一个 method 调用? 'getAllProducts' 参数是什么?就像 apos.singleton(data.page , 'getAllProducts' , 'widget-name') ?我真的很想知道这些论点。如果第一个论点是我可以用方法调用任何模块,那也应该适用,对吧?或者它只适用于 apostrophe-pages 模块?
    • getAllProducts 是您分配给模块的全新方法的名称,self.on 使用第三个参数中的函数方便地为您创建。完全等价于写“self.getAllProducts = ... code here ...; self.on('apostrophe-pages:beforeSend', 'getAllProducts').
    • 第一个参数是模块的名称和该模块发出的事件。有些模块会发出事件,有些则不会。撇号页面发出 beforeSend 这特别有用,因为它是在页面呈现之前发出的,并且是您在 JavaScript 中进行异步工作的最后机会。我们正在编写一份完整指南,以了解发出并可以通过这种方式侦听的标准事件。
    • 哇,谢谢!这个新功能承诺事件绝对有用!再次感谢您的帮助并提供深入的解释。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-20
    • 2015-03-17
    • 1970-01-01
    • 2011-06-29
    • 1970-01-01
    • 2011-03-19
    相关资源
    最近更新 更多