0

I create config value in system.xml that contain src of a script tag
how can i call this value in view\frontend\layout\default.xml file in head tag

2 Answers 2

0

You have to create custom block and insert in default.xml like this:

<referenceBlock name="head.components">
    <block class="\Test\Test\Block\TestBlock" name="test" template="Test_Test::template.phtml" before="-" />
</referenceBlock>

And your Test\Test\Block\TestBlock can look like this:

class TestBlock extends \Magento\Framework\View\Element\Template
{
    private \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig;

    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        array $data = []
    ) {
        parent::__construct($context, $data);
        $this->scopeConfig = $scopeConfig;
    }

    public function getScriptSrcConfig(): string
    {
        return $this->scopeConfig->getValue('path/to-your/config');
    }
}

and in templtate you just use

<?= /** @noEscape */ $block->getScriptSrcConfig() ?>

P.S. There is a better way from technical perspective, but it's more difficult - https://devdocs.magento.com/guides/v2.4/extension-dev-guide/view-models.html

2
  • Thank you for your answer, is there a way to do it with helper like this kishansavaliya.com/magento2/…
    – Jad
    Jul 28, 2021 at 13:26
  • yes, it's possible, you can pass some helper method which gets config into block arguments, but anyway it would be required to execute block in template Jul 29, 2021 at 9:47
0

First create a Helper class and call get the config value inside the helper. use that helper value in template file. you can directly call from helper to phtml file or from helper -> block-> phtml file [ there are different ways too but I used it most of the time] refer this link for details of code. https://vrajeshpatel.in/2021/05/22/how-to-create-system-xml-configuration-and-get-data-from-system-configuration-in-magento-2/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.