Search code examples
htmljekyllliquidhtml-heading

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


I am trying to get some headlines from my post. I have this code currently

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

However extract_element is not a function, how will I be able to achieve this?

Thank you


Solution

  • Considering your posts consist of the following content:

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

    Then we split its content until we get the desired heading:

    {% 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!" 
    

    Then {{ h2_content }} produces:

    "I'm a heading!"