Question

I want to load store logo image URL in javascript so i can bind it to my knockout element, how can i achieve that?

Was it helpful?

Solution

To get store logo url. You need to add this below code in your block :

<?php

namespace RH\Helloworld\Block;

class CustDetails extends \Magento\Framework\View\Element\Template
{
    protected $logo;    
    
    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Theme\Block\Html\Header\Logo $logo,
        array $data = []
    )
    {        
        $this->logo = $logo;
        parent::__construct($context, $data);
    }
  
    public function getStoreLogoUrl()
    {    
        return $this->logo->getLogoSrc(); // Return Logo Url
    }   
}
?>

After that, you need to get this value in your phtml file and pass that value using <script type="text/x-magento-init"> like this below way :

<?php
    $logoUrl = $block->getStoreLogoUrl();
?>

<div id="m2-component" data-bind="scope:'ko'">
<script type="text/x-magento-init">
    {
        "#m2-component": {
            "Magento_Ui/js/core/app": {
               "components": {
                    "ko": {
                        "component": "RH_Helloworld/js/myjs",
                        "template" : "RH_Helloworld/myjs",
                        "logoUrl": <?= /* @escapeNotVerified */ $logoUrl ?>
                    }
                }
            }
        }
    }
    </script>
</div>

Now, You to get value in js file add this below js code in your js file :

myjs.js

define(['uiComponent', 'ko', 'jquery'], function (Component, ko, jquery) {

    return Component.extend({
        initialize: function (config) {
            var self = this;
            this._super();
            console.log(config.logoUrl);
        },
});

Hope, It's helpful for you.

OTHER TIPS

There is no direct method to have store logo in JS. However, you can pass the logo URL in configprovider and get it in knockout JS file for the solution.

You can use mage-x-init and pass logo as arguments json.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top