我想列出我帖子中的所有标签,当然只有一个标签,所以没有几个标签。
我尝试将它放在一个字符串中,用空格分隔它们,然后从字符串中循环出每个单词,给它们uniq过滤器:
{% capture alltags %}
{% for story in site.stories %}
{{ story.tags | join: ' ' }}
{% endfor %}
{% endcapture %}
{% for word in alltags %}
{{ word | uniq }}
{% endfor %}
我得到了单词之间的空格,但它们不是uniq。我确实需要它们单独循环,以便我可以在它们上建立链接。
像这样的东西会起作用。
{% comment %} compiling the gross list of all tags, duplicates and all {% endcomment %}
{% for post in site.posts %}
{% assign tags = tags | concat:post.tags %}
{% endfor %}
{% comment %} Getting rid of duplicates (uniq), sorting it - all in one go {% endcomment %}
{{ tags | uniq | sort }}
如果你试试这个,你就会明白发生了什么。
{% capture alltags %}
{% for story in site.stories %}
{{ story.tags | join: ' ' }}
{% endfor %}
{% endcapture %}
alltags : {{ alltags | inspect }}
{% for word in alltags %}
word : {{ word | inspect }}
uniq : {{ word | uniq }}
{% endfor %}
alltags
是一个字符串,而不是数组。
当你遍历alltags
时,唯一发生的循环包含word
变量,它是一个等于alltags
本身的字符串。
实际上你需要在数组上应用uniq
过滤器。
如果您运行此代码,您将看到差异:
{% comment %} create an empty array {% endcomment %}
{% assign tagsArray = "" | split:"" %}
{% for story in site.stories %}
{% assign tagsArray = tagsArray | concat: story.tags %}
tagsArray : {{ tagsArray | inspect }}
{% endfor %}
tagsArray : {{ tagsArray | inspect }}
{% assign tagsArray = tagsArray | uniq %}
tagsArray uniq : {{ tagsArray | inspect }}