简体   繁体   中英

How can I obtain key and value of a hash in Jekyll / liquid?

I have a Jekyll page with the following setup:

---
navigation:
 - FOO: foo
 - BAR: bar
 - BAZ: baz
---

<h3>
  <a name="{{ page.navigation[0][1] }}" class="anchor" 
     href="#{{ page.navigation[0][1] }}">
  </a>{{ page.navigation[0][0] }}
</h3>

<p>Lorem ipsum dolor sit amet,.</p>

...

<h3>
  <a name="{{ page.navigation[1][1] }}" class="anchor" 
     href="#{{ page.navigation[1][1] }}">
  </a>{{ page.navigation[1][0] }}
</h3>

<p>Different content ...</p>

...

<h3>
  <a name="{{ page.navigation[2][1] }}" class="anchor" 
     href="#{{ page.navigation[2][1] }}">
  </a>{{ page.navigation[2][0] }}
</h3>

<p>Another different content ...</p>

...

I am trying to use the key and value of each navigation item in my front matter with the href links in the example above.

I can not use {% for %} iterations because inside each paragraph is a different content.

My desire is to have Jekyll output the following code:

<h3>
  <a name="foo" class="anchor" href="#foo">
  </a>FOO
</h3>

<p>Lorem ipsum dolor sit amet,.</p>

...

<h3>
  <a name="bar" class="anchor" href="#bar">
  </a>BAR
</h3>

<p>Different content ...</p>

...

<h3>
  <a name="baz" class="anchor" href="#baz">
  </a>BAZ
</h3>

<p>Another different content</p>

...

Any ideas how to do this?

You could warp a for loop around each item in navigation like this:

<h3>
    {% for item in page.navigation[0] %}
     <a name="{{ item[1] }}" class="anchor" 
        href="#{{ item[1] }}">
     </a>{{ item[0] }}
     {% endfor %}
</h3>

<p>Lorem ipsum dolor sit amet,.</p>

<h3>
    {% for item in page.navigation[1] %}
     <a name="{{ item[1] }}" class="anchor" 
        href="#{{ item[1] }}">
     </a>{{ item[0] }}
     {% endfor %}
    </h3>

<p>Different content ...</p>


<h3>
    {% for item in page.navigation[2] %}
     <a name="{{ item[1] }}" class="anchor" 
        href="#{{ item[1] }}">
     </a>{{ item[0] }}
     {% endfor %}
    </h3>

<p>Another different content</p>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM