Checking run mode from Sightly HTL in AEM

Sometimes during development, we would need to check the run mode in our AEM environment, so we can show different content based on the context. From the Sightly HTL API, it’s possible to check for the wcmmode, but not the runmode.

In this article, we will set up a sling model helper which will be a sling model, and then use Sightly HTL, data-sly-use, API, to access which run mode we are in. How to check runmode in AEM Sightly HTL can never be this easy


Sightly Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!--/* Production */-->
<sly data-sly-use.checkRunMode="${'com.sourcedcode.core.models.utils.CheckRunModeHelper' @ runmode='develop'}">
  <sly data-sly-test="${checkRunMode.hasRunMode}">
    <h1>In Development</h1>
  </sly>
</sly>

<!--/* Staging */-->
<sly data-sly-use.checkRunMode="${'com.sourcedcode.core.models.utils.CheckRunModeHelper' @ runmode='staging'}">
  <sly data-sly-test="${checkRunMode.hasRunMode}">
    <h1>In Staging</h1>
  </sly>
</sly>

<!--/* Production */-->
<sly data-sly-use.checkRunMode="${'com.sourcedcode.core.models.utils.CheckRunModeHelper' @ runmode='production'}">
  <sly data-sly-test="${checkRunMode.hasRunMode}">
    <h1>In Production</h1>
  </sly>
</sly>

Java Sling Model

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package com.sourcedcode.core.models.utils;

import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.models.annotations.Default;
import org.apache.sling.models.annotations.Model;
import org.apache.sling.models.annotations.injectorspecific.OSGiService;
import org.apache.sling.models.annotations.injectorspecific.RequestAttribute;
import org.apache.sling.settings.SlingSettingsService;

import javax.annotation.PostConstruct;

@Model(adaptables = SlingHttpServletRequest.class)
public class RunModeHelper {

    @OSGiService
    private SlingSettingsService slingSettingsService;

    @RequestAttribute
    @Default(values = "nan")
    private String runmode;

    private boolean hasRunMode = false;

    @PostConstruct
    public void init() {
        String runModes = slingSettingsService.getRunModes().toString();
        hasRunMode = runModes.contains(runmode);
    }

  public boolean getHasRunMode() {
    return hasRunMode;
  }
}

Was this post helpful?

Hello, I am an active Adobe Community Advisor & a certified Lead AEM Developer who is currently working as a Senior AEM Full Stack Developer. I have over a decade of overall web engineering experience and many years (more than 6) of AEM experience in practice. I hope to give back to the AEM Full Stack Development community by sharing my knowledge with the world.

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top