Просмотр исходного кода

changed where action takes place

sou 7 лет назад
Родитель
Сommit
065d0e1340
2 измененных файлов с 59 добавлено и 5 удалено
  1. 56 2
      lib/models/page.js
  2. 3 3
      lib/routes/page.js

+ 56 - 2
lib/models/page.js

@@ -528,13 +528,67 @@ module.exports = function(crowi) {
   };
 
   // find all templates applicable to the new page
-  pageSchema.statics.findAllTemplates = function(pathList) {
+  pageSchema.statics.findTemplate = function(pathList, templatePath) {
     const Page = this;
     const regexpList = pathList.map(path => new RegExp(`${path}/[_@]template`));
 
     return Page
       .find({path: {$in: regexpList}})
-      .populate({path: 'revision', model: 'Revision'});
+      .populate({path: 'revision', model: 'Revision'})
+      .then(templates => {
+        return fetchTemplate(templates, templatePath);
+      });
+  };
+
+  const cutOffLastSlash = path => {
+    const lastSlash = path.lastIndexOf('/');
+    return path.substr(0, lastSlash);
+  };
+
+  const assignTemplateByType = (templates, path, type) => {
+    for (let i = 0; i < templates.length; i++) {
+      if (templates[i].path === `${path}/${type}template`) {
+        return templates[i];
+      }
+    }
+  };
+
+  const assignGlobalTemplate = (globalTemplates, path) => {
+    const globalTemplate = assignTemplateByType(globalTemplates, path, '_');
+    if (globalTemplate) {
+      return globalTemplate;
+    }
+
+    if (path === '') {
+      return;
+    }
+
+    const newPath = cutOffLastSlash(path);
+    return assignGlobalTemplate(globalTemplates, newPath);
+  };
+
+  const fetchTemplate = (templates, templatePath) => {
+    let templateBody;
+    /**
+     * get local template
+     * @tempate: applicable only to immediate decendants
+     */
+    const localTemplate = assignTemplateByType(templates, templatePath, '@');
+
+    /**
+     * get global templates
+     * _tempate: applicable to all pages under
+     */
+    const globalTemplate = assignGlobalTemplate(templates, templatePath);
+
+    if (localTemplate) {
+      templateBody =  localTemplate.revision.body;
+    }
+    else if (globalTemplate) {
+      templateBody = globalTemplate.revision.body;
+    }
+
+    return templateBody;
   };
 
   // find page by path

+ 3 - 3
lib/routes/page.js

@@ -314,9 +314,9 @@ module.exports = function(crowi, app) {
       const templatePath = cutOffLastSlash(originalPath);
       const pathList = generatePathsOnTree(originalPath, []);
 
-      return Page.findAllTemplates(pathList)
-        .then(templates => {
-          renderVars.template = fetchTemplate(templates, templatePath);
+      return Page.findTemplate(pathList, templatePath)
+        .then(template => {
+          renderVars.template = template;
         });
     })
     // get list pages