【问题标题】:Iterate over hashes in liquid templates迭代液体模板中的哈希
【发布时间】:2012-01-02 15:50:40
【问题描述】:

我正在 Jekyll 中编写一个使用 Liquid 的网站。

我希望页面看起来像这样:

---
title: Designing algorithms that scale horizontally
speaker: Luke Ehresman, CopperEgg
category: notes.mongodallas.talks
links:
 - demo: http://www.github.com/copperegg/mongo-scaling-demo
layout: talknotes
---

在 Liquid 中,YAML 的链接部分如下:

[{'demo' => 'http://www.github.com/copperegg/mongo-scaling-demo' }]

我希望能够遍历数组,执行如下操作:

<a href="{{ link.value }}">{{ link.key }}</a>

但是到目前为止我的任何想法都失败了。

【问题讨论】:

    标签: liquid jekyll


    【解决方案1】:

    当您使用名为 hash 的变量对哈希进行迭代时,hash[0] 包含键,hash[1] 包含每次迭代的值。

    {% for link_hash in page.links %}
      {% for link in link_hash %}
        <a href="{{ link[1] }}">{{ link[0] }}</a>
      {% endfor %}
    {% endfor %}
    

    【讨论】:

    • 代码有效,只是不像您预期​​的那样。请注意,我说的是遍历哈希。我添加了更多代码来为您提供上下文。
    • 嗯,现在看起来确实像是一个答案,而不是电报。更新了我的投票以反映这一点。
    • 我对你的 sn-p 有点困惑:你能把 _hash 添加到你的 frontmatter 变量中以使其工作吗?
    • @user3411192 对不起,我不明白你的意思。
    • 关于这个问题,前面有一个名为links的“哈希列表”。第一个循环遍历该列表 (page.links),每次获取一个哈希值。我将这些哈希中的每一个称为link_hash。要遍历每个link_hash 的键,我需要第二个循环,我在其中使用了link。在我的示例中,hash 正在由 link 播放。
    【解决方案2】:

    我会在 YAML 中这样定义它们:

    links:
      demo: http://www.github.com/copperegg/mongo-scaling-demo
    

    然后迭代:

    {% for link in page.links %}
      <a href="{{ link[1] }}">{{ link[0] }}</a>
    {% endfor %}
    

    【讨论】:

    • 这绝对是更好的选择。问题中的 YAML 在links 下的列表中冗余地有一个散列。该列表可以删除。上面的答案令人困惑,因为它首先尝试遍历列表,然后遍历哈希,这是完全没有必要的,而这个答案避免了。
    【解决方案3】:
      {% for link in page.links %}
          {% for item in link %}
            <a href="{{ item[0] }}">{{ link[1] }}</a>
          {% endfor %}
        {% endfor %}
    

    我有一个非常相似的问题,但我的变量中有多个项目,所以我使用了未记录的 item 变量,它完成了工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-22
      • 2023-04-07
      • 2014-11-29
      • 1970-01-01
      相关资源
      最近更新 更多