创建呈现模板的静态路由

Creating static routes that render templates

我正在尝试在 /profile、/account 或 /account/profile.

上创建一个页面(在撇号多站点项目中,因此每个站点都会存在一个唯一的页面)

我在 /sites/lib/modules/account-profile/index.js 下面创建了以下内容,并从 How Apostrophe handles requests 页面对其进行了改编:

module.exports = {
  afterConstruct: function(self) {
    self.addDispatchRoutes();
  },
  construct: function(self, options) {
    self.addDispatchRoutes = function() {
      self.dispatch("/account/:profile", self.showPage);
    };
    self.showPage = function(req, callback) {
      return (
        req.params.profile,
        (err, doc) => {
          // handle err, if no err...
          if (!doc) {
            // Let Apostrophe render the 404 page
            req.notFound = true;
          }
          req.template = self.renderer("profile", { doc: doc });
          return callback(null);
        }
      );
    };
  }
};

包括后:

"account-profile": {
   extend: "apostrophe-custom-pages"
 }

在app.js

我遇到的问题是当我点击 /account/profile.

时 showPage 函数从不运行

我理解匹配 /account/profile 位的 :profile 位有点可疑,但我也不知道如何在执行类似以下操作时呈现模板:

self.apos.app.get("/account/profile", async function(req, res, callback) {
  req.template = self.renderer("profile", { doc: "hi" });
  // now what?
});

我想我遗漏了一些非常简单的东西,但我已经非常彻底地扫描了文档,但找不到那个遗漏的部分。

您的底部示例非常接近!为了在静态路由上创建页面,我通常倾向于使用您在问题中显示的相同代码。为了从 apos.app.get 中 return 一个页面,你需要做这样的事情:

self.apos.app.get('/account/profile', function(req, res){
    // Place any data you need to access in your template here:
    req.data = {};

    // self.sendPage is what will actually return the page and render the template 'profile.html' in your views folder.
    // You can change 'profile' to the name of your template minus '.html' - e.g. 'page.html' would just be 'page'
    return self.sendPage(req, 'profile', {});
});

您丢失的部分似乎是 sendPage。该方法实际上将使用该方法的第二个参数中指定的模板呈现页面。

如果您将其放入您的构造方法中,您将在您的网站上拥有一条新路线,您可以通过转至 /account/profile 访问该路线。它将呈现位于模块的视图文件夹中的模板。

我最初在此页面上找到此信息:

https://apostrophecms.org/docs/technical-overviews/how-apostrophe-handles-requests.html

在 'Rendering a full HTML page from a route' 部分。