我正在尝试遍历我的内容树,并从各种标记文件中提取元数据。我看到了分页器插件的例子,但我觉得我的用例比分页器所需要的要简单得多。
如果我的目录结构看起来像这样:
projects/
project-name-1/
index.md
project-name-2/
index.md
project-name-3/
index.md我想遍历我的内容并检索所有的"title“元数据属性。如果我在jade中尝试一个简单的循环,例如:
each project in content.projects
- console.log(project.metadata.title);我的日志未定义。
我试着将这种逻辑转移到一个受分页器(用js编写)启发的简单插件中:
module.exports = function(env, callback){
_ = require('underscore');
var options = {projects: 'projects'};
function getProjects(contents) {
//helper that returns a list of projects found in *contents*
//note that each article is assumed to have its own directory in the articles directory
// console.dir(contents[options.projects]);
_.each(contents[options.projects], function(i){console.log(i);});
var projects = {};//@todo create a new collection containing each metadata object
return projects;
}
//add the article helper to the environment so we can use it later
env.helpers.getProjects = getProjects;
//tell the plugin manager we are done
callback();
};虽然我能够在记录的对象中看到我的元数据,但我不完全确定如何从这里访问它。有没有像这样从内容树中提取元数据的更简单的方法?任何帮助都是非常感谢的!
发布于 2015-12-12 00:17:40
你遇到的问题是你正在迭代一个对象,而不是一个数组。
你可以用两种方法来解决这个问题,要么使用wintersmith的“内容组”,即数组。
each project in contents.projects._.directories
- console.log(project.index.metadata.title)请注意,我们在这里迭代目录,因为这反映了您的设置,如果您的项目只在一个目录中,我们将迭代'pages‘内容组。
另一种选择是使用'for in‘枚举。在jade中,它看起来像这样:
each name, content in contents.projects
- console.log(content.index.metadata.title)这种方法的问题是,如果您将目录以外的内容放入“项目”中,它将会崩溃。
https://stackoverflow.com/questions/34209178
复制相似问题