Jekyll / liquid 模板在 <h2> 标签中获取文本

Jekyll / liquid template get text if it is in a <h2> tag

我正试图从我的 post 中获得一些头条新闻。我目前有这个代码

{% assign sub_navigation = content | extract_element: 'h2' %}
{% for item in sub_navigation %}
  <li><a href="#{{ item.id }}">{{ item.text }}</a></li>
{% endfor %}

但是extract_element不是一个函数,我怎样才能实现这个?

谢谢

考虑到您的帖子包含以下内容:

out of heading
<h2>I'm a heading!</h2>
<p>This is a paragraph</p>

然后我们拆分它的内容,直到我们得到想要的标题:

{% assign h2_open_start = content|split: '<h2'%}
 # ["out of heading\n", ">I'm a heading!</h2>\n<p>This is a paragraph</p>\n"]

{% assign h2_open_end = h2_open_start[1]| split: '>'%}
# ["", "I'm a heading!</h2", "\n<p", "This is a paragraph</p", "\n"]

{% assign h2_content_array = h2_open_end[1]| split: '</h2'%}
# ["I'm a heading!"]

{% assign h2_content = h2_content_array[0]%}
#"I'm a heading!" 

然后 {{ h2_content }} 产生:

"I'm a heading!"

如果您不介意依赖关系,将 jekyll-extract-element gem 添加到 gem 文件中,原始 post 中的代码将起作用。这是我在 CloudCannon 网站上看到的一个常见片段,这个 gem 也是他们写的。