简体   繁体   English

如何使用 Pug 将 Markdown 文件的目录转换为 HTML 页面?

[英]How to use Pug to convert a directory of Markdown files into HTML pages?

I'm starting to use Pug templating我开始使用 Pug 模板

I've got a directory with some markdown files that I'd like to turn into HTML pages我有一个目录,其中包含一些 markdown 文件,我想将其转换为 HTML 页面

legal/
    privacy-policy.md
    refund-policy.md
    terms-of-service.md

So far, I've thought to place a .pug file alongside each到目前为止,我一直在考虑在每个文件旁边放置一个.pug文件

legal/
    privacy-policy.md
  + privacy-policy.pug
    refund-policy.md
  + refund-policy.pug
    terms-of-service.md
  + terms-of-service.pug

The .pug files are all very similar, "boilerplatey" -- they extend the same template: .pug文件都非常相似,“样板”——它们扩展了相同的模板:

extends ../layout.pug

block lead
  title Privacy Policy

block content
  .content
    include:markdown-it(linkify) privacy-policy.md

This works for now, but it clearly doesn't scale这暂时有效,但显然无法扩展

How can I do better than this?我怎样才能做得比这更好? What's the best way to iterate the .pug boilerplate over each markdown file in the directory?在目录中的每个 markdown 文件上迭代.pug样板的最佳方法是什么?

I'd move all the code to do this back into the route (ie into node.js itself), where you have access to the fs file system library .我会将所有代码移回路由(即进入 node.js 本身),在那里您可以访问fs 文件系统库

To list all the documents do something like this:要列出所有文档,请执行以下操作:

router.get('/', function(req, res){

  var folder = 'legal';
  var fs= require('fs');
  var fileList = [];

  fs.readdir(folder, function(err, files){
    files.forEach(function(file){
      fileList.push(file);
    });
  })

  res.render('directory', {"files": fileList});

}

Then to read a file in use a url parameter:然后使用 url 参数读取文件:

router.get('/:fileName', function(req, res){

  var fileName = 'legal/' + req.params.fileName + '.md';
  var fs= require('fs');

  fs.readFile(fileName, 'utf8', function(err, data) {
    if (err) throw err;

    res.render('contract', {"title": req.params.fileName, "text": data});


});

In your pug template for the contracts just output the variable as rendered using interpolation:在您的 pug 合约模板中,只需输出使用插值呈现的变量:

!{text}

You could also get fancy with the title using something like SugarJS titleize which will dynamically create a proper title from the file name.您还可以使用诸如SugarJS titleize 之类的东西来欣赏标题,它会根据文件名动态创建正确的标题。

It's too late an answer, but it might be useful to someone.答案为时已晚,但它可能对某人有用。 There is an npm package md-pug-to-html有一个 npm package md-pug-to-html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM