【问题标题】:Can I create and manipulate a Map in jekyll liquid?我可以在 jekyll 液体中创建和操作地图吗?
【发布时间】:2019-12-31 18:51:11
【问题描述】:

我想在处理表格时计算总和,所以渲染是逐行进行的,但我需要对列进行总计,我需要每列一个计数器。

{% assign cols = "col1,col2" | split: "," %}
{% assign rows = "row1,row2" | split: "," %}
{% assign total = ????? %}
...
{% for row in rows %}
  <tr>
  {% for col in cols %}
    <td>
    {% for post in site.posts %}
      {% if post.colThing == col and post.rowThing == row %}
        {% assign total[row] = total[row] | plus: post.thatNumber %}
        .... {{ post.thatNumber }} ...
      {% endif %}
    {% endfor %}
    </td>
  {% endfor %}
  </tr>
{% endfor %}
<tr>
{% for col in cols %}
  <td>
  .... {{ total[row] }} ...
  </td>
{% endfor %}
</tr>

我能想到的最好办法是再次解析site.posts 的总数:

...
<tr>
{% for col in cols %}
  {% assign total = 0 %}
  {% for post in site.posts %}
    {% if post.colThing == col %}
      {% assign total = total | plus: post.thatNumber %}
    {% endif %}
  {% endfor %}
  <td>
  .... {{ total }} ...
  </td>
{% endfor %}
</tr>

这是获得总数的最有效方法吗?

【问题讨论】:

    标签: jekyll liquid


    【解决方案1】:

    除了 Jekyll 无法操作 ruby​​ 哈希之外,您使用哈希来存储总数的想法很明显。 total[row] 是一个哈希条目,不能从液体中填充。

    您打印总计的方式是解决方案之一。

    在效率方面,如果您想通过使用wherewhere_exp 过滤器来避免每次要填充单元格时循环遍历所有帖子,那么探索另一种方式可能会很有趣。根据您处理的帖子数量,这可能会更有效:

    {% assign cols = "col1,col2" | split: "," %}
    {% assign rows = "row1,row2" | split: "," %}
    
    <thead><tr>{% for col in cols %}<th>{{ col }}</th>{% endfor %}</tr></thead>
    
    {% for row in rows %}
      <tr>
      {% for col in cols %}
        <td>
        {% comment %}
        where_exp: "post", "post.colThing == col and post.rowThing == row"
          returns null if no post fulfill conditions
          or
          returns an array of posts fulfilling conditions
    
        first
          returns the first post of the returned array
        {% endcomment %}
        {% assign post = site.posts | where_exp: "post", "post.colThing == col and post.rowThing == row" | first %}
    
        {% if post != null %}
          {{ post.title }} : {{ post.thatNumber }}
        {% else %}
          NO DATAS AT THIS POSITION
        {% endif %}
        </td>
      {% endfor %}
      </tr>
    {% endfor %}
    
    <tfoot><tr>
    {% for col in cols %}
      {% assign total = 0 %}
      {% comment %}
      Select posts that are in each column
      {% endcomment %}
      {% assign posts = site.posts | where: "colThing", col %}
      {% for post in posts %}
        {% assign total = total | plus: post.thatNumber %}
      {% endfor %}
      <td>{{ total }}</td>
    {% endfor %}
    </tr></tfoot>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-28
      • 2016-09-13
      • 2019-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-04
      相关资源
      最近更新 更多