Using Feature Flags
How to enable feature flags in your templates.
Twig #
Use craft.featureFlags.isEnabled() to check whether a flag is enabled for the current user.
Conditional block
{% if craft.featureFlags.isEnabled('new-hero') %}
{% include '_partials/hero-v2' %}
{% else %}
{% include '_partials/hero' %}
{% endif %}
Ternary for swapping a component
{% set layout = craft.featureFlags.isEnabled('wide-layout') ? 'wide' : 'default' %}
{% include '_layouts/' ~ layout %}
Custom bucket key
Pass a second argument to override the default bucketing identifier. This is useful when you want rollout bucketing tied to something other than the current user ID (e.g. a company account or session ID).
{% set companyId = currentUser.companyId %}
{% if craft.featureFlags.isEnabled('bulk-export', companyId) %}
<a href="{{ url('export/bulk') }}">Bulk Export</a>
{% endif %}
How evaluation works #
When you call isEnabled(), the plugin evaluates the flag in a fixed order. The first condition that produces a definitive result wins.
- Flag exists? — If the flag handle doesn’t match any flag, return
false. - Enabled toggle — If the flag’s master toggle is off, return
false. - Expiration — If the flag has an expiration date that is in the past, return
false. - Global on — If the flag has no targeting rules and no rollout percentage, return
true(the flag is globally on). - Targeting rules — Each rule is evaluated in order. If any rule matches, return
true. See Targeting Rules. - Percentage rollout — If a rollout percentage is set and greater than 0, compute the user’s bucket. If the bucket falls within the percentage, return
true. See Percentage Rollouts. - Default — If nothing matched, return
false.
PHP #
Use the EvaluationService to check flags from PHP code:
use craftquest\featureflags\FeatureFlags;
$isEnabled = FeatureFlags::getInstance()->evaluationService->isEnabled('new-hero');
| Parameter | Type | Description |
|---|---|---|
$flagName | string | The flag handle |
$user | ?User | A specific user to evaluate against. Defaults to the currently logged-in user in web requests, or null in console requests. |
$bucketKey | ?string | A custom identifier for percentage rollout bucketing. Overrides the default (user ID). |
Passing a specific user
use craft\elements\User;
use craftquest\featureflags\FeatureFlags;
$user = User::find()->email('[email protected]')->one();
if (FeatureFlags::getInstance()->evaluationService->isEnabled('beta-dashboard', $user)) {
// show beta dashboard for this user
}
Passing a custom bucket key
use craftquest\featureflags\FeatureFlags;
// Roll out by company rather than by individual user
$companyId = (string) $currentUser->companyId;
if (FeatureFlags::getInstance()->evaluationService->isEnabled('bulk-export', null, $companyId)) {
// enable bulk export for this company
}