Uniq 液体过滤器标签在字符串中循环单词时不起作用



我想列出我帖子中的所有标签,当然只有一个标签,因此没有一个标签。

我尝试将其放在字符串中,用一个空间将它们分开,然后从字符串中循环每个单词,从而给它们提供Uniq滤波器:

{% capture alltags %}
{% for story in site.stories %}
{{ story.tags | join: ' ' }}
{% endfor %}
{% endcapture %}
{% for word in alltags %}
{{ word | uniq }}
{% endfor %}

我在单词之间得到了空间,但它们不是uniq。我确实需要它们单独循环,以便在它们上链接。

如果尝试此操作,您将了解发生的事情。

{% 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 }}

类似的东西会起作用。

{% 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 }}

最新更新