【问题标题】:Eleventy - define start and end point for excerptEleventy - 定义摘录的起点和终点
【发布时间】:2021-06-25 14:33:04
【问题描述】:

我正在尝试找到一种方法来选择性地在内容中的某处选择摘录,即能够定义摘录的起点和终点。

我尝试了Eleventy's docs 方法来解析内容的摘录。但这会解析分隔符 .

之上的所有内容

使用{{ post.data.page.excerpt }}选择

---
pageTitle: blog
tags: posts
---
Everything here is parsed as the excerpt
<!-- excerpt -->
Lorem ipsum, dolor sit amet consectetur adipisicing elit.
...

我尝试的另一种方法是在前面使用一个键来单独指定介绍/摘录,但这种方法不允许我使用现有内容。

{{ post.data.intro }}

---
pageTitle: blog
tags: posts
intro: This is an excerpt stored in a key
---
Lorem ipsum, dolor sit amet consectetur adipisicing elit.
...

目前是否有一种方法可以为要从内容中提取的摘录指定开始和结束分隔符?例如:

---
pageTitle: blog
tags: posts
---
#Heading of the blog

Lorem ipsum, dolor sit amet consectetur adipisicing elit...

<!-- excerptStart -->
This part should be the excerpt of the post
<!-- excerptEnd -->
...

任何帮助将不胜感激!

【问题讨论】:

  • 经过进一步研究,我偶然发现了一个链接到另一个博客的博客,该博客提供了一个可行的解决方案。如果感兴趣,请参阅答案部分了解更多详情。

标签: eleventy


【解决方案1】:

经过更多研究,我发现了这个博客,它提供了一个可行的解决方案。

https://keepinguptodate.com/pages/2019/06/creating-blog-with-eleventy/ (感谢原作者)

简而言之,您可以使用“简码”完全控制摘录处理。只需将此函数添加到您的 eleventy.js 文件中即可。

module.exports = function (eleventyConfig) {
  eleventyConfig.addShortcode("excerpt", article => extractExcerpt(article));
};

function extractExcerpt(article) {
  if (!article.hasOwnProperty("templateContent")) {
    console.warn(
      'Failed to extract excerpt: Document has no property "templateContent".'
    );
    return null;
  }

  let excerpt = null;
  const content = article.templateContent;

  // The start and end separators to try and match to extract the excerpt
  const separatorsList = [
    { start: "<!-- Excerpt Start -->", end: "<!-- Excerpt End -->" },
    { start: "<p>", end: "</p>" },
  ];

  separatorsList.some(separators => {
    const startPosition = content.indexOf(separators.start);
    const endPosition = content.indexOf(separators.end);

    if (startPosition !== -1 && endPosition !== -1) {
      excerpt = content
        .substring(startPosition + separators.start.length, endPosition)
        .trim();
      return true; // Exit out of array loop on first match
    }
  });

  return excerpt;
}

然后你可以在你的markdown文件中添加&lt;!-- Excerpt Start --&gt;和&lt;!-- Excerpt End --&gt;来指定你想要使用的内容的哪一部分作为摘录。

要使用摘录短代码,只需将{% excerpt post %} 添加到主页模板即可。

您可以参考上面链接的原始博客了解详细分类。

我还测试了一个没有花里胡哨的简单版本。有兴趣可以去看看:https://github.com/enrichdev-en/eleventy-excerpt-example。

【讨论】:

    猜你喜欢
    • 2014-01-03
    • 2017-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多