2

The newer versions of Craft CMS stimulate using environment variables in the CP. It works perfectly. I have set two variables for sites in my .env file:

DUTCH_SITE_URL="http://company.test"
ENGLISH_SITE_URL="http://company.test/en"

One thing that's not clear to me is the right way to request the baseUrl in templates. For example: I'm using a simple language switcher to switch between two languages:

{% set sites = craft.app.sites.getAllSites() | without(currentSite) %}
{% for site in sites %}
  <li><a href="{{ site.baseUrl }}" title="{{ site.language }}">{{ site.language }}</a></li>
{% endfor %}

When viewing the Dutch website the language switcher shows the link to the English website. The problem is that site.baseUrl outputs the environment variables instead of the English site url. The link looks like this:

http://company.test/$ENGLISH_SITE_URL

What's the proper way to deal with this?

1 Answer 1

2

You can get it to return the url using the siteUrl function and passing it a siteId parameter. So do:

{% set sites = craft.app.sites.getAllSites() | without(currentSite) %}
{% for site in sites %}
   <li><a href="{{ siteUrl(siteId=site.id) }}" title="{{ site.language }}">{{ site.language }}</a></li>
{% endfor %}

I don't know if it's the best way but it works :)

3
  • But what is the reason for the above behaviour? Outputting craft.app.sites gives me [baseUrl] => '$BASE_URL_DE' , it's like the env var is not being parsed
    – Urs
    Oct 25, 2020 at 9:33
  • aha github.com/craftcms/cms/issues/4098
    – Urs
    Oct 25, 2020 at 9:35
  • {% set baseUrl = craft.app.sites.currentSite.getBaseUrl()%} works for me
    – Urs
    Oct 25, 2020 at 9:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.