How can I get sites by their group handle/name within twig templates?
Documentation only mentions querying sites by group id - getSitesByGroupId
.
3 Answers
If you already have a reference to a Site
model (i.e. the global currentSite
Twig variable), you can get other sites in that group, like this:
{% set currentSiteGroup = currentSite.group %}
{% set sitesInGroup = currentSiteGroup.sites %}
{# Bonus — Remove the current site from that list: #}
{% set otherSitesInGroup = sitesInGroup|without(currentSite) %}
I would rather suggest you to do that in PHP but the Twig way would be the following
{% set allSites = craft.app.getSites().getAllSites() %}
{% set sitesWithGroup = [] %}
{% for site in allSites %}
{% if site.getGroup().name == 'my group name' %}
{% set sitesWithGroup = sitesWithGroup|merge([site]) %}
{% endif %}
{% endfor %}
-
Thanks! I think i will turn it into macro. And about php, i prefear to do things in twig when its possible, its just less posibility to break something. Commented Feb 28, 2019 at 11:08
-
Wait, I can't make macro using this, macro returns only strings. Oh, well. Commented Feb 28, 2019 at 18:04
-
That's why you usually want to do it in PHP since it's less likely to break and you have more possiblies + it's less resource heavy Commented Feb 28, 2019 at 19:38
I find Twig/Craft filters to be the most concise and readable for things like this.
{% set allSites = craft.app.sites.getAllSites() %}
{% set filteredSites = allSites|filter(s => s.group == 'My Group Name') %}
More useful filters here