2

I try to better understand the concept of text/x-magento-init.

I understand that it allows us to define script components that do a certain task, which we then can use as often as we like in any template.

I found this example in vendor\magento\module-theme\view\frontend\templates\js\cookie.phtml

<script type="text/x-magento-init">
    {
        "*": {
            "mage/cookies": {
                "expires": null,
                "path": "<?= $block->escapeJs($block->getPath()) ?>",
                "domain": "<?= $block->escapeJs($block->getDomain()) ?>",
                "secure": false,
                "lifetime": "<?= $block->escapeJs($block->getLifetime()) ?>"
            }
        }
    }
</script>

By reading the documentation, I figured out that this means, a script is getting called once (because of the *). But where do I find the component mage/cookies to understand what it does exactly? And what if I use body instead of *, how does this change the logic?

Bonus Question: How to define our own component?

| improve this question | | | | |
2

mage/cookies is JS component which initialized on the element with the selector specified as element selector.

Syntax :

<script type="text/x-magento-init">
{
    // components initialized on the element defined by selector
    "<element_selector>": {
        "<js_component1>": ...,
        "<js_component2>": ...
    },
    // components initialized without binding to an element
    "*": {
        "<js_component3>": ...
    }
}
</script>

If you'll add body instead of * then, it will consider as element_selector.

If you'll add * then it will provide data without selector.

For more details, You can check here.

| improve this answer | | | | |
  • But where is mage/cookies defined, where can I inspect its code? – Black Feb 18 at 13:16
  • You can check here : lib/web/mage/cookies.js – Rohan Hapani Feb 18 at 13:42
  • And if I want to create my own, do I have to put it in my theme or there? And when does it make sense to use an element selector? – Black Feb 18 at 13:59
  • You can use in theme as well as in module also. It's depend on your requirement. – Rohan Hapani Feb 19 at 4:25
  • I guess I have to create the same folder structure in my theme e.g. mytheme/base/lib/mycustom.js ? – Black Feb 19 at 10:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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