5

I'm developing Magento 2.1 application with two logos:

  1. Light logo on the home page.
  2. Dark logo for all other pages.

By default, theme uses dark logo. I've created a custom page layout for home page. In this layout, I attempted to override logo's logo_file argument. After flushing cache and all static assets, home page does not show logo defined in page layout.

Magento_Theme/layout/default.xml

...
<referenceContainer name="header-wrapper" htmlClass="bmg-header-container bmg-header-inverse container">
            <!-- logo -->
            <container name="header-logo-container" htmlTag="div" htmlClass="header-logo-container">
                <referenceBlock name="logo">
                    <arguments>
                        <argument name="logo_file" xsi:type="string">images/logo_dark_sm.png</argument>
                        <argument name="logo_img_width" xsi:type="number">164</argument>
                        <argument name="logo_img_height" xsi:type="number">59</argument>
                    </arguments>
                </referenceBlock>
            </container>
            <!-- /logo -->
            ...
</referenceContainer>
...

Attempt 1 - Magento_Theme/page_layout/custom_home.xml

...
<referenceContainer name="header-wrapper">
    <referenceContainer name="header-logo-container">
        <referenceBlock name="logo">
            <arguments>
                <argument name="logo_file" xsi:type="string">images/logo_light_sm.png</argument>
            </arguments>
        </referenceBlock>
    </referenceContainer>
</referenceContainer>
...

Attempt 2 - Magento_Theme/page_layout/custom_home.xml

...
<referenceContainer name="header-logo-container">
    <referenceBlock name="logo">
        <arguments>
            <argument name="logo_file" xsi:type="string">images/logo_light_sm.png</argument>
        </arguments>
    </referenceBlock>
</referenceContainer>
...

Any guidance would be much appreciated!

4 Answers 4

4

Create helper to change logo dynamically

Override default.xml in your theme and add helper in logo_file argument

Magento_Theme/layout/default.xml

<argument name="logo_file" xsi:type="helper" helper="Vendor\Module\Helper\Data::getLogo"></argument>

In your helper, you can get logo based on current url like this.

<?php

namespace Vendor\Module\Helper;

class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
    protected $_request;

    public function __construct
    (
        \Magento\Framework\App\Request\Http $request
    ) {
        $this->_request = $request;
    }

    public function getLogo()
    {
        if ($this->_request->getFullActionName() == 'cms_index_index') {
            $logo =  'images/logo_light_sm.png';
        } else {
            $logo = 'images/logo_dark_sm.png';
        }

        return $logo;
    }
} 
3
  • That did the trick! Could you please explain why I should not use the objectManager directly?
    – MParsons
    May 27, 2017 at 16:34
  • 1
    There are several reasons. The code will work, but it is best practice to not reference the ObjectManager class directly. Please refer this for more details magento.stackexchange.com/q/117098 May 27, 2017 at 17:09
  • I am using multi website and for the Korea site i tried above way but getting wrong image src path (it includes src path site_url/pub/static/version/en_US/...) due to which logo is not showing ...so i overrided logo.phtml file into my theme and used helper into this which works fine for me. Oct 8, 2020 at 10:13
3

The better way to do this will be using helper function. in your Magento_Theme/layout/default.xml you can pass argument for logo like this-

<argument name="logo_file" xsi:type="helper" helper="Namespace\ModuleName\Helper\Data::getLogoImage"></argument>

and then in your helper file you can return logo based on current url, Your helper file-

public function __construct(
    \Magento\Framework\View\Element\Template\Context $context,
    \Magento\Framework\App\Request\Http $objectManager
)
{

    $this->_objectManager = $objectManager;
}        

public function getLogoImage()
    {

        $fullAction =  $this->_objectManager->getFullActionName();;
        if($fullAction == 'cms_index_index')
        {
            $logo =  'images/logo_light_sm.png';
        }
        else
        {
            $logo = 'images/logo_dark_sm.png';
        }
        return $logo;
    }
3

I tried, this is working for me very well.

Magento_Cms/layout/cms_index_index.xml:

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="logo">
            <arguments>
                <argument name="logo_file" xsi:type="string">images/logo_light_sm.png</argument>
            </arguments>
        </referenceBlock>
    </body>
</page>

This solution is no better than creating helper class?

1
  • This is the correct answer. Dec 21, 2018 at 16:03
0

I have given configuration to upload Light and dark logo, you can see here:-

enter image description here

System.xml:-

<field id="logo_homepage" translate="label" type="image" sortOrder="20" showInDefault="1" showInWebsite="1" >
                    <label>Logo For Homepage</label>
                    <backend_model>YourNamespace\YourModule\Model\Config\Backend\Image</backend_model>
                    <base_url type="media" scope_info="1">logo</base_url>
                </field>
                 <field id="logo_otherthan_homepage" translate="label" type="image" sortOrder="20" showInDefault="1" showInWebsite="1" >
                    <label>Logo For Other Pages</label>
                    <backend_model>YourNamespace\YourModule\Model\Config\Backend\Image</backend_model>
                    <base_url type="media" scope_info="1">logo</base_url>
                    <comment>Logo except homepage.</comment>
 </field>

And then overrided logo.phtml file into my theme. used helper into this .phtml file to set uploaded dark and light logo of the configuration into the src of logo.phtml.

YourNamespace\YourModule\Model\Config\Backend\Image.php:-

<?php

namespace YourNamespace\YourModule\Model\Config\Backend;

class Image extends \Magento\Config\Model\Config\Backend\Image
{
    /**
     * The tail part of directory path for uploading
     *
     */
    const UPLOAD_DIR = 'logo'; // Folder save image

    /**
     * Return path to directory for upload file
     *
     * @return string
     * @throw \Magento\Framework\Exception\LocalizedException
     */
    protected function _getUploadDir()
    {
        return $this->_mediaDirectory->getAbsolutePath($this->_appendScopeInfo(self::UPLOAD_DIR));
    }

    /**
     * Makes a decision about whether to add info about the scope.
     *
     * @return boolean
     */
    protected function _addWhetherScopeInfo()
    {
        return true;
    }

    /**
     * Getter for allowed extensions of uploaded files.
     *
     * @return string[]
     */
    protected function _getAllowedExtensions()
    {
        return ['jpg', 'jpeg', 'gif', 'png', 'svg'];
    }


}

YourNamespace\YourModule\Helper\Data.php:-

<?php

namespace YourNamespace\YourModule\Helper;

use Magento\Framework\App\Helper\AbstractHelper;

use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Model\ScopeInterface;

/**
 * Created by Carl Owens (carl@partfire.co.uk)
 * Company: PartFire Ltd (www.partfire.co.uk)
 **/
class Data extends AbstractHelper
{
    /**
     * @var \Magento\Framework\App\Http\Context
     */
    private $httpContext;

    /**
     * Scope config
     *
     * @var ScopeConfigInterface
     */
    protected $scopeConfig;

   
    const LOGO_HOMEPAGE = 'section/group/logo_homepage';

    const LOGO_OTHERTHAN_HOMEPAGE = 'section/group/logo_otherthan_homepage';

    const LOGO_FOLDER_NAME = 'logo';

    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        ScopeConfigInterface $scopeConfig,
        \Magento\Framework\App\Request\Http $request
    ) {
        parent::__construct($context);
        $this->scopeConfig = $scopeConfig;
        $this->_request = $request;
    }


    


    public function getLogo()
    {
        $scope = ScopeInterface::SCOPE_STORE;

        $folderName = self::LOGO_FOLDER_NAME;

        $logoUrl = '';

        if ($this->_request->getFullActionName() == 'cms_index_index') {
            $logo = $this->scopeConfig->getValue(self::LOGO_HOMEPAGE, $scope);
        } else {
            $logo = $this->scopeConfig->getValue(self::LOGO_OTHERTHAN_HOMEPAGE, $scope);
        }

        if (!empty($logo)) {
            $storeLogoPath = $logo;

            $path = $folderName . '/' . $storeLogoPath;

            $logoUrl = $this->_urlBuilder
                ->getBaseUrl(['_type' => \Magento\Framework\UrlInterface::URL_TYPE_MEDIA]) . $path;
        }
        return $logoUrl;
    }
}

app\design\frontend\ThemnNamespace\Themname\Magento_Theme\templates\html\header\logo.phtml:-

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

// @codingStandardsIgnoreFile

/**
 * @var \Magento\Theme\Block\Html\Header\Logo $block
 */
?>
<?php
    $helper = $this->helper('YourNamespace\YourModule\Helper\Data');
    $logoSrc = $helper->getLogo()!='' ? $helper->getLogo() : $block->getLogoSrc() ;
?>
<?php $storeName = $block->getThemeName() ? $block->getThemeName() : $block->getLogoAlt();?>
<span data-action="toggle-nav" class="action nav-toggle"><span><?= /* @escapeNotVerified */ __('Toggle Nav') ?></span></span>
<a
    class="logo"
    href="<?= $block->getUrl('') ?>"
    title="<?= /* @escapeNotVerified */ $storeName ?>"
    aria-label="store logo">
    <img src="<?= /* @escapeNotVerified */ $logoSrc ?>"
         title="<?= $block->escapeHtmlAttr($block->getLogoAlt()) ?>"
         alt="<?= $block->escapeHtmlAttr($block->getLogoAlt()) ?>"
         <?= $block->getLogoWidth() ? 'width="' . $block->getLogoWidth() . '"' : '' ?>
         <?= $block->getLogoHeight() ? 'height="' . $block->getLogoHeight() . '"' : '' ?>
    />
</a>

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.