I need to dynamically change a value in Twig templates by selecting a configuration value (defined in a custom module) based on the current environment.
I did the following in a Form class, which works fine:
/**
* Generate parent site Base URL per environment.
*
* @return string
* The parent site Base URL used in all templates site-wide.
*/
public function getBaseUrl() {
$host = $this->requestStack->getCurrentRequest()->getHost();
$config = $this->configFactory->get('clientname_cta_base.settings');
switch ($host) {
case 'resources.clientname.com':
// Set $base_url to Production environment.
$base_url = $config->get('prod_base_url') ?? [];
break;
case 'uatresources.clientname.com':
// Set $base_url to UAT environment.
$base_url = $config->get('uat_base_url') ?? [];
break;
case 'qaresources.agencyname.com':
case 'qaresources.clientname.com':
// Set $base_url to QA environment.
$base_url = $config->get('qa_base_url') ?? [];
break;
default:
// All other environments, including local, link to Dev.
$base_url = $config->get('dev_base_url') ?? [];
break;
}
return $base_url;
}
/**
* Generate CTA destination URL per environment.
*
* @return string
* The CTA destination URL used in all templates site-wide.
*/
public function getCtaUrl() {
$config = $this->configFactory->get('clientname_cta_base.settings');
$cta_url = $this->getBaseUrl() . $config->get('default_link_dest') ?? [];
return $cta_url;
}
This displays the desired URL paths in two disabled fields when the SettingsForm
is loaded:
// Active URL configuration (read-only).
$form['clientname_cta_base_computed_base_url'] = [
'#type' => 'textfield',
'#title' => $this->t('Computed base URL (Preview)'),
'#default_value' => $this->getBaseUrl(),
'#description' => $this->t('Read-only value based on config and environment. Save changes to update.'),
'#attributes' => ['disabled' => 'disabled'],
];
$form['clientname_cta_base_computed_cta_url'] = [
'#type' => 'textfield',
'#title' => $this->t('Computed CTA URL (Preview)'),
'#default_value' => $this->getCtaUrl(),
'#description' => $this->t('Read-only value based on config and environment. Save changes to update.'),
'#attributes' => ['disabled' => 'disabled'],
];
I could even store these updated values in configuration when the SettingsForm
is submitted -- but that will not quite get me what I want.
These values need to be computed dynamically by selecting config based on the value of $host
at runtime -- importing the Dev environment's computed config values to the QA environment won't do. So I am looking for a way to call the module's public methods (getBaseUrl()
and getCtaUrl()
) in either theme preprocess or Twig templates.
Is this approach possible? Should I have used theme settings instead?
getBaseUrl
andgetCtaUrl
. Inject the service into the form, for Twig call the helper service in theme preprocess and pass down the values. (don't forget to add cache context/tags)