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!

| improve this question | | | | |
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.

| improve this answer | | | | |
  • 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 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 at 17:09
  • 1
    Something must not be right -- it's saying the alias isn't defined. See the article for details. – andrew.welch Mar 8 at 20:30

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.