I'm using preparse field plugin to limit the amount of tags a user can add to his account. I've modified the code slightly so the tags are processed as a comma, separated, list
.
The plan is to integrate Selectize with the search form, so that users can choose from all available tags. As I can't use relatedTo
, it'll have to involve some manipulation. I understand it isn't considered best practice to do this with Twig, but I'm not versed in PHP to build a plugin (I'm learning Python so Twig will have to do!).
The code below sets a variable to allow access to a merged array, I know there's a similar post (I'd also like to avoid duplicates, but Selectize will ignore them anyway) but I'm struggling to follow that example and use it for my requirements.
Code below:
{% set users = craft.users.group('verified') %}
{% set merged = [] %}
{% for user in users %}
{% set tags = user.tagsSpecialismSearchable %}
{% set specialisms = tags|split(', ') %}
{% for specialism in specialisms %}
{# Merge the tag arrays #}
{% set merged = specialisms|merge(specialisms) %}
{% endfor %}
<ul>
{# Test the output #}
{% for specialism in specialisms %}
<li>{{specialism}}</li>
{% endfor %}
</ul>
{% endfor %}
{# Output the merged array #}
<ul>
{% for mergedSpecialism in merged %}
<li>{{ mergedSpecialism }}</li>
{% endfor %}
</ul>
I know I'm setting merged
in the wrong place, as all it outputs is a duplicate of the last specialisms
array. So how would I loop through all users and output the available tags?
I'm probably missing some conditionals to check if the user has actually set tags, so any advice in layman's terms appreciated!
Updated: Working code (Thanks @kcolls)
{% set users = craft.users.group('verified') %}
{% set merged = [] %}
{% for user in users %}
{% set tags = user.tagsSpecialismSearchable %}
{% set specialisms = tags|split(', ') %}
{% for specialism in specialisms %}
{# Check if specialism already merged #}
{% if specialism not in merged %}
{# Merge each specialism #}
{% set merged = merged|merge([specialism]) %}
{% endif %}
{% endfor %}
<ul>
{# Test the output #}
{% for specialism in specialisms %}
<li>{{specialism}}</li>
{% endfor %}
</ul>
{% endfor %}
{# Output the merged array #}
<ul style="background: blue; color: white;">
{% for mergedSpecialism in merged %}
<li>{{ mergedSpecialism }}</li>
{% endfor %}
</ul>
For an added bonus, sort the array alphabetically:
<ul>
{% for mergedSpecialism in merged|sort %}
<li>{{ mergedSpecialism }}</li>
{% endfor %}
</ul>