【问题标题】:Jekyll: DRY'ing up partials using same HTML structureJekyll:使用相同的 HTML 结构干燥部分
【发布时间】:2017-04-13 20:17:51
【问题描述】:

在我的 Jekyll 网站中,每个页面在底部附近都有一个部分。每种类型的部分文本各不相同,但 HTML 结构是相同的。为了说明......

文件夹结构:

_includes
  - partial1.html
  - partial2.html
pages
  - page1.html
  - page2.html
  - page3.html

partial1.html

<div class="container">
  <h3>Buy now</h3>
  <p>It'll be the best decision you ever made.</p>
</div>

partial2.html

<div class="container">
  <h3>Sign up for our newsletter</h3>
  <p>We won't spam you (too much).</p>
</div>

page1.html

---
layout: default
title: Page 1
---

...

{% include partial1.html %}

page2.html

---
layout: default
title: Page 2
---

...

{% include partial2.html %}

page3.html

---
layout: default
title: Page 3
---

...

{% include partial2.html %}

现在部分只是复制 HTML 结构,但我更喜欢注入具有唯一值的主模板。如果您可以在包含文件夹中使用 frontmatter,那将是一种清理方法,但 Jekyll 不支持。

处理这种情况的最佳方法是什么?

(如果我的问题不清楚,请告诉我,我会尝试通过其他示例代码来澄清。)

【问题讨论】:

  • 举个例子有助于全面理解问题。
  • 现在清楚一点了吗?
  • 是的,更清楚了,但我不太了解“主模板”是什么,您的意思是避免在两个部分中重复结构的解决方案?
  • 是的,没错

标签: html jekyll dry


【解决方案1】:

部分文本可以在每个部分或数据文件中,因此 html 将在另一个中:

在每个部分

一个主partial.html持有html结构:

<div class="container">
    <h3>{{include.h}}</h3>
    <p>{{include.p}}</p>
</div>

然后每个部分将使用包含变量调用它:

  • partial1.html

    {% assign header = "Buy now" %}
    {% assign paragraph = "It'll be the best decision you ever made." %}
    {% include partial.html h=header p=paragraph%}
    
  • partial2.html

    {% assign header = "Sign up for our newsletter" %}
    {% assign paragraph = "We won't spam you (too much)." %}
    {% include partial.html h=header p=paragraph%}
    

使用数据文件

  • 创建一个包含文本的文件_data/partial.yml

    buy:
        h: "Buy now"
        p: "It'll be the best decision you ever made."
    sign:
        h: "Sign up for our newsletter"
        p: "We won't spam you (too much)."
    

然后在每个部分使用数据:

  • 部分1.html:

     {% include partial.html type="buy"%}
    
  • partial2.html:

     {% include partial.html type="sign" %}
    
  • 在每个页面中:(例如:page1.html)

    ---
    layout: default
    title: Page 1
    ---
    
    ...
    
    {% include partial1.html %}
    

【讨论】:

    猜你喜欢
    • 2017-09-24
    • 1970-01-01
    • 2020-08-27
    • 2018-04-05
    • 2016-02-21
    • 2014-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多