我在我的网站中使用了 Jekyll 的 Collections 来解决与您类似的问题。
集合在 Jekyll 中仍然是一个实验性功能,我使用的解决方案本身就很 hacky,但如果你不太喜欢它,它就足够易于管理了。
如需更详细、更友好的收藏介绍,请here's a great post about getting started with them。
我们需要记住的一件事是,我们应该远离此类情况的帖子。
正如 Ben Balter 在上面的链接中提到的,“如果人们将博客文章用于非博客文章,那么 Jekyll 已经失败了”。 食谱不是帖子,我们应该尽可能避免使用它们。
话虽如此,我的方法分为三个步骤:
创建两个集合(我们的自定义帖子类型)——假设它们是“食谱”和“成分”
找到一种将它们相互关联的方法 - 确保“生菜”将列在“沙拉”下
在“食谱”中包含相关的“成分” - 添加液体代码以在“沙拉”页面的某处实际显示来自“生菜”的信息。
第 1 步
为您的每个集合创建 _ingredients 和 _recipes 文件夹(确保以复数形式命名它们)并将它们添加到您的 _config.yml 文件中:
collections:
ingredients:
output: true
recipes:
output: true
permalink: /recipes/:path/
output: true 参数为集合中的每个项目创建一个单独的 HTML 页面,permalink(可选)允许您控制 URL。
第 2 步
在你的 lettuce.md 集合项的 YAML front-matter 中添加这样的元数据:
---
parent-collection: salad
---
如果lettuce.md 属于多个配方,您可以添加多个。如果需要说明,请务必在元数据下方添加内容:
---
parent-collection:
- salad
- hamburguer
- taco
---
Lettuce is really good for your health, but it kinda sucks as a food.
请注意,salad、hamburguer 和 taco 的名称应与配方 URL slug 完全相同,否则将无法正常工作(即 greatrecipes.com/recipes/salad)。如果您的食谱名称是一个句子,请将其括在引号中。
这个变量稍后会被 slugified,所以像 parent-collection: The Amazing Souflè Français 这样的名字会匹配 the-amazing-soufle-francais。尽管如此,还是会发生奇怪的事情:如有疑问,只需写小写字母salad。
这是 hacky 部分。
第 3 步
为您的食谱创建一个特定的布局(如_layout/recipe-page.html)并添加下面的代码——我们将在此处将配料包含到食谱页面中。
记住你的食谱(salad.md 和朋友)应该指向这个布局。
{% capture current_collection %}{{ page.url | remove: "recipes" | remove: "/" | remove: " " }}{% endcapture %}
这里我们从 URL 中获取配方的名称并将其分配给 current_collection 变量。确保在单行中这样做,因为将其设置为多行会在捕获的字符串中添加一堆空格并破坏您的代码 10/10 次。 疯狂。 em>
<div class="recipe-content">
<p>{{ content }}</p> -- This is the content of the current recipe in the collection, your "post text".
</div>
{% for ingredient in site.ingredients %}
{% capture captured_parent_collection %}{{ ingredient.parent-collection | slugify }}{% endcapture %} -- This capture is just to pass the slugify filter and sanitize parent.collection to make sure it matches the URL slug
{% if captured_parent_collection == current_collection %}
<div class="recipe-ingredient">
<h3>{{ ingredient.name }}</h3> -- "<h3>Lettuce</h3>"
<p>{{ ingredient.content }}</p> -- "<p>Lettuce is really good for your health, but it kinda sucks as a food.</p>"
</div>
{% endif %}
{% endfor %}
匹配此食谱的成分,并将它们中的每一种都包含在布局中。耶!
您的每种成分都应该出现在您的食谱文本下方。
请注意,您并没有像您在问题中描述的那样将成分放入食谱文本中,而是将它们包含在其后面的布局中。据我所知,您不能真正在帖子/收藏文本的中间添加内容 — 除非您通过 Jekyll 的自定义插件破解自己的方式。
当然有不那么老套的方法来做到这一点,但这就是我让它发挥作用的方式。如果您在自己尝试此操作时遇到任何问题,请告诉我 - 以及其他任何人,请随时纠正我。
我的网站正在进行此设置 - 看看 the layout where I pull in my child collection items 和 the metadata on the child collection items 本身。