In Magento 2, there are two types of template files. One is .phtml and second one is .html files under web/template directory.
In .phtml we easily get the config value, but it’s tricky to get config value in web template files which we are going to cover in this article.
You have to follow below steps :
Step 1 : Add below code to your web .js file:
app/code/[Vendor]/[ModuleName]/view/frontend/web/js/[DirectoryName]/[JsFileName].js
define([
'ko',
'jquery',
'uiComponent',
'mage/storage',
'mage/url'
], function (ko, $, Component, storage, url) {
'use strict';
return Component.extend({
defaults: {
template: 'Vendor_ModueName/[DirectoryName]/[TemplateFileName]'
},
getconfigSettingValue: function () {
var serviceUrl = url.build('modulename/configsetting/settingfieldid');
storage.get(serviceUrl).done(
function (response) {
if (response.success) {
return response.value
}
}
).fail(
function (response) {
return response.value
}
);
return false;
}
});
});
Step 2 : Create controller
app/code/[Vendor]/[ModuleName]/Controller/[DirectoryName]/ControllerFileName.php
Add below code
namespace [Vendor][ModuleName]Controller[DirectoryName];
class ControllerFileName extends MagentoFrameworkAppActionAction
{
protected $resultJsonFactory;
protected $storeManager;
protected $scopeConfig;
public function __construct(
MagentoFrameworkAppActionContext $context,
MagentoFrameworkControllerResultJsonFactory $resultJsonFactory,
MagentoStoreModelStoreManagerInterface $storeManager,
MagentoFrameworkAppConfigScopeConfigInterface $scopeConfig
) {
$this->resultJsonFactory = $resultJsonFactory;
$this->storeManager = $storeManager;
$this->scopeConfig = $scopeConfig;
parent::__construct($context);
}
/**
* Execute view action
*
* @return MagentoFrameworkControllerResultInterface
*/
public function execute()
{
$response = [];
try {
$configValue = $this->scopeConfig->getValue(
'your/path/config',
MagentoStoreModelScopeInterface::SCOPE_STORE
);
$response = [
'success' => true,
'value' => __($configValue)
];
} catch (Exception $e) {
$response = [
'success' => false,
'value' => __($e->getMessage())
];
$this->messageManager->addError($e->getMessage());
}
$resultJson = $this->resultJsonFactory->create();
return $resultJson->setData($response);
}
}
Step 3 : Get config value as per below code in .html file.
<div class="config-setting-value" data-bind="html: getconfigSettingValue"></div>

