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

问题描述 投票:0回答:2

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

我尝试将它放在一个字符串中,用空格分隔它们,然后从字符串中循环出每个单词,给它们uniq过滤器:

{% capture alltags %}

{% for story in site.stories %}

{{ story.tags | join: ' ' }}

{% endfor %}

{% endcapture %}

{% for word in alltags %}

{{ word | uniq }}

{% endfor %}

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

tags liquid uniq
2个回答
1
投票

像这样的东西会起作用。

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

1
投票

如果你试试这个,你就会明白发生了什么。

{% 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 }}
© www.soinside.com 2019 - 2024. All rights reserved.