16

Is there a way to check what environment craft is running on - ie, dev or not dev - via the template.

For example:

{%if env is 'dev'%}
    hello dev
{% else %}
   hello world
{% endif %}
22

When developing locally on Craft you would most likely have devMode => true set in your config file and set to false for your production config.

app/config/general.php

return array(
 'mydevdomain.dev' => array(
   'devMode' => true
 ),
 'mylivedomain.com' => array(
   'devMode' => false
 )
);

So you could test whether craft is in dev mode and respond to that:

{% if craft.config.devMode %}
  You are in dev mode
{% else %}
  You are not in devmode
{% endif %}
  • You can also define totally custom variables in the same way (e.g. 'cache' => false{% if craft.config.cache %}) – carlcs Aug 12 '14 at 10:32
  • 1
    In my opinion, this is a risky thing to do: it's not inconceivable that an inexperienced developer might be tempted to switch on dev mode in production to debug something 'guerilla' style, which could in turn trigger these conditionals unintentionally. Yes, that's a bad idea, but it could happen. Other devs might even switch on devMode in production by accident. – James Smith Mar 30 at 14:35
22

In Craft 3 you can get the env using the getenv() function:

{% set env = getenv('ENVIRONMENT') %}

{% if env == 'dev' %}
    hello dev
{% else %}
    hello world
{% endif %}

Or via the app’s config service:

{% set env = craft.app.config.env %}
  • This really helped with setting up some new custom environment variables outside of the default Craft 3 ones for a project. 👍🏼 – Jay Aug 20 '18 at 13:30
  • This worked wonders! Thanks. Very handy when you want to work off local files in dev, but need the absolute URL on the production site. – mateostabio Mar 12 at 16:34
  • THank for this simple answer. – Sameera Thilakasiri Sep 18 at 8:33
7

You can set a custom "environment label" variable inside config/general.php:

return array(
    // ALL ENVIRONMENTS
    '*' => array(
    ),
    // LOCAL
    'mysite.local' => array(
        'env' => 'local'
    ),
    // DEV
    'dev.mysite.com' => array(
        'env' => 'dev'
    ),
    // PROD
    'www.mysite.com' => array(
        'env' => 'prod'
    )
);

Then use the craft.config variable to output the env variable for the current environment:

{% if craft.config.env == 'dev' %}
    hello dev
{% else %}
    hello world
{% endif %}

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.