如何在 metalsmith 中设置多个内容区域?

How do I set up multiple content areas in metalsmith?

我有一个非常简单的 metalsmith 用例,似乎没有任何现成的文档涵盖。

在我的 index.html 中,我想要多个内容区域:

<!-- in my index html -- a single page landing site -->
<body>
  <section id="about">
     {{{about}}}
  </section>
  <section id="faq">
     {{{faq}}}
  </section>
...

我希望 aboutfaq 的内容来自降价文件。 我很乐意更改我的文件 organised/marked 的方式。

我只是想不出要使用哪些插件才能使其正常工作,一切似乎都旨在为每个源文件生成一个输出文件。

看起来可以工作的插件 (metalsmith-in-place and metalsmith-layouts) 告诉您来 SO 以获得更详细的示例,所以我们来了!

您可以使用支持模板继承的语言(如 swig)结合 metalsmith-in-place 来创建多个内容区域。

如果不使用 markdown,你可以这样做:

src/index.swig

{% extends 'templates/default.swig' %}

{% block about %}
  Content for about
{% endblock %}

{% block faq %}
  Content for faq
{% endblock %}

templates/default.swig

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
</head>
<body>
  <section id="about">
    {% block about %}{% endblock %}
  </section>
  <section id="faq">
    {% block faq %}{% endblock %}
  </section>
</body>
</html>

build.js

/**
 * Dependencies
 */
var filenames = require('metalsmith-filenames');
var inPlace = require('metalsmith-in-place');
var metalsmith = require('metalsmith');

/**
 * Build
 */
metalsmith(__dirname)

  // Process templates
  .use(filenames())
  .use(inPlace('swig'))

  // Build site
  .build(function(err){
    if (err) throw err;
  });

然后运行node build.js。现在,如果你也想使用降价,这实际上是不可能的。 Marked 是 metalsmith-markdown 的渲染器,它将用 <p> 包围您的内容,转义某些字符等等。这将使维护模板变得麻烦,因为 metalsmith-markdown 可能会破坏 swig 标签。它可能仍然有效,但我绝对不会推荐它。

所以我推荐的是上面的设置。您将失去使用降价的优势,但会获得一些额外的组织选项。由您决定您更喜欢哪个。

正如其他评论和答案所提到的,使用数据降价、就地和具有继承的模板引擎将使这成为可能。上面唯一缺少的部分是以正确的顺序将它们放在一起(我发现 Metalsmith 通常就是这种情况)。

先就地使用,再使用data-markdown:

metalsmith(__dirname)
  .use(inplace({
    engine: 'swig',
    pattern: '**/*.html',
    autoescape: false,
  }))
  .use(markdown({
  }))
  .build(function(err) {
    if (err) {
        console.log(err);
    }
    else {
        console.info('✫ Built it. ✫');
    }
  });

data-markdown 标签包装你的降价:

<div data-markdown>

## About

This is about me. I like lists:

* They
* Make
* Me
* So
* Happy!

</div>

将其包含在某处:

<!DOCTYPE html>
<html>
<head><title>A page</title></head>
<body>

  {% include "./markdown/about.md" %}

  {% include "./markdown/faq.md" %}

</body>

此处的工作演示:https://github.com/hoosteeno/metalsmith-markdown-swig/

我为 metalsmith-markdown 创建了一个分支:

https://github.com/DKhalil/metalsmith-markdown

您可以像这样在 markdown 文件中添加部分:

Markdown text here
---
section: SECTION_NAME
---
Markdown text here

第二个降价部分将在模板文件中的变量 SECTION_NAME 下可用,第一个仍在 {{ contents }}