4

Sites localized versions are setup using Base URL like this:

— http://{baseUrl}/en/
— http://{baseUrl}/fr/

But {baseUrl} variables are not transformed using craft.app.sites.getAllSites().

{% set sites = craft.app.sites.getAllSites() %}
{% for site in sites %}
    {{ site.baseUrl }}
    // → outputs http://{baseUrl}/locale/ instead of http://mywebsite.com/en/
{% endfor %}

Whereas baseUrl are set from general.php:

'aliases' => array(
    'basePath' => '/mywebsite.com/htdocs/',
    'baseUrl'  => 'http://www.mywebsite.com/'
),
8

So as of Craft CMS 3 RC7, they added a new alias() Twig function.

So what you can do is something like this in your general.php:

'aliases' => [
    '@basePath' => getenv('CRAFTENV_BASE_PATH'),
    '@baseUrl' => getenv('CRAFTENV_BASE_URL'),
],

(or whatever/however you want to set them). These aliases can be used in sites’ Base URL settings, volumes’ Base URL settings, and Local volumes’ File System Path settings in the AdminCP.

And then in your templates, you can do something like:

{{ alias('@baseUrl') }}
{{ alias('@baseUrl/assets/img/' }}

To resolve the alias there. I changed Craft 3 Multi-Environment to leverage aliases in this way (rather than having them in the .custom config), and it's documented in detail in the Asset Volumes and Aliases.

You do not need to be using Craft 3 Multi-Environment to utilize them in the same way, this is just a live example that's handy to point to.

1

You have to use aliases in order to make that work Docs

In your config (just a snipped from us, we don't insert the links and folders manually and use the $_SERVER variables to generate them)

'aliases' => [
    'assetPath' => $publicPath . DIRECTORY_SEPARATOR . 'assets' . DIRECTORY_SEPARATOR,
    'assetUrl'  => $server . 'assets/',
    'basePath'  => $publicPath . DIRECTORY_SEPARATOR,
    'baseUrl'   => $server,
],

So you can insert something like

@assetPath/general

as your base volume path or for your sites

@baseUrl/en/

those aliases will be parsed automatically

  • 1
    Thank you! The at sign (@) writting is working fine for my assets' base URL volumes. But this is not working for my sites' base URL: http://@baseUrl/international/en/ in settings → I get baseurl/international/en in front-end. Also for sites, is it possible to set a dynamic base URL protocol using a variable? Because if http(s):// is deleted in profit of the at sign (@) variable, after Save an http is automatically added at the beginning of this URL. – Romain Poirier Jan 12 '18 at 9:10

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.