25

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 %}
nicael
  • 2,382
  • 7
  • 27
  • 48
bravokiloecho
  • 1,583
  • 4
  • 17
  • 22

4 Answers4

40

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 %}

There's a bit more information about the .env file in the docs for Environmental Configuration.

kr37
  • 1,355
  • 9
  • 18
26

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 %}
Alec Ritson
  • 4,529
  • 1
  • 19
  • 34
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 %}
kmgdev
  • 1,169
  • 1
  • 9
  • 17
3

I know this is an old question, but just an update:

If you're on Craft CMS v3+, craft.config.[setting-name] has been deprecated. Use craft.app.config.general.[setting-name] instead.

So if you wanted to check if you were in dev environment, you'd do craft.app.config.general.devMode, this returns a boolean value.

Mage
  • 31
  • 2