1

I am currently developing a multilingual craft website. To include assets like styles and scripts, I have so far built the URL following the pattern "{{ siteUrl }}/assets/css/main.css".

However, as soon as I change from German to English in the frontend of the website, the siteUrl changes, too, so that the styles and scripts can't be found anymore.

Is there another global variable, like {root_url} in expressionengine, which returns only the URL of the primary website or the root URL, regardless of the chosen language or site?

thanks!

1 Answer 1

4

You can define whatever aliases/environment variables you like. In this case, I'd probably define an environment variable in my .env file like this:

BASE_WEB=http://example.com

And then in config/general.php I'd add an alias:

<?php
/**
 * General Configuration
 *
 * All of your system's general configuration settings go in here. You can see a
 * list of the available settings in vendor/craftcms/cms/src/config/GeneralConfig.php.
 *
 * @see craft\config\GeneralConfig
 */

return [
    // Craft config settings from .env variables
    'aliases' => [
        '@baseWeb' => getenv('BASE_WEB'),
    ],
];

And then to use this in a template, you'd just do:

{{ alias('@baseWeb/assets/css/main.css') }}

...and away you go. To learn more, check out the Flat Multi-Environment Config for Craft CMS 3 article.

3
  • thank you very much for this answer! I'm fairly new to craft and never really understood the env/alias-possibilities, so this article is really helpful! thanks again!!
    – Matthias
    Mar 8, 2020 at 15:58
  • mmh, I tried this approach but get "Invalid Argument – yii\base\InvalidArgumentException" (…) if ($throwException) { throw new InvalidArgumentException("Invalid path alias: $alias"); }… but I did exactly as your example.
    – Matthias
    Mar 8, 2020 at 17:09
  • 1
    Something must not be right -- it's saying the alias isn't defined. See the article for details. Mar 8, 2020 at 20:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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