我正在尝试计算并列出Jekyll中名为_note
的Collection内的标签。我认为,我非常接近解决这个问题,但我对标签的实际计数(列出唯一标签工作正常)有点绊倒,并且可以使用第二双眼睛来查看液体标记看看我错过了什么。
_note
YAML标头中的标签组织为:
tags: [tag1, tag2, tag3, tag4]
到目前为止:
<!-- Create empty arrays -->
{% assign tags = '' | split: ',' %}
{% assign unique_tags = '' | split: ',' %}
{% assign counter = 0 %}
<!-- Map and flatten -->
{% assign note_tags = site.note | map: 'tags' | join: ',' | split: ',' %}
<!-- Push to tags -->
{% for tag in note_tags '%}
{% assign tags = tags | push: tag %}
{% endfor %}
<!-- Uniq -->
{% assign tags = tags | sort %}
{% for tag in tags %}
<!-- If not equal to previous then it must be unique -->
{% unless tag == previous %}
<!-- Push to unique_tags and count -->
{% assign unique_tags = unique_tags | push: tag %}
{% assign counter = counter | plus: 1 %}
{% endunless %}
{% assign previous = tag %}
{% endfor %}
{% for tag in unique_tags %}
{{ tag }} ({{ counter }}
{% endfor %}
在液体中使用size
方法似乎没有返回正确的值。
答案 0 :(得分:3)
{% comment %}map, flatten and sort{% endcomment %}
{% assign tags = site.note | map: 'tags' | join: ',' | split: ',' | sort %}
{% assign previousTag = "" %}
{% assign counter = 0 %}
{% for currentTag in tags %}
{% comment %}first loop : initializing previousTag{% endcomment %}
{% if previousTag == "" %}
{% assign previousTag = currentTag %}
{% endif %}
{% if currentTag == previousTag %}
{% assign counter = counter | plus: 1 %}
{% else %}
{{ previousTag }} ({{ counter }})
{% assign counter = 1 %}
{% endif %}
{% comment %}last loop : flushing what's left to print{% endcomment %}
{% if forloop.last %}
{{ currentTag }} ({{ counter }})
{% endif %}
{% assign previousTag = currentTag %}
{% endfor %}
{% assign uniq_tags = site.note
| map: 'tags'
| join: ","
| split: ","
| uniq %}
<p>{{ uniq_tags | array_to_sentence_string }}</p>
答案 1 :(得分:0)
我在GitHub托管页面上使用Jekyll,您可以使用group_by
实现以下目的:
{% assign alldocs = site.COLLECTIONNAME | <additional filtering and sorting> %}
{% assign grouptag = alldocs | map: 'tags' | join: ',' | split: ',' | group_by: tag %}
{%- for tag in grouptag -%}
<h1>{{- tag.name -}} - {{tag.size}}</h1>
{%- for document in alldocs -%}
{% if document.tags contains tag.name %}
<p>{{- document.title -}}
{% endif %}
{%- endfor -%}
{%- endfor -%}
标签云的实时示例,其中包括我博客的所有内容(帖子和项目)here