Jorgeska
Jorgeska

Reputation: 468

Custom favicon in Yii2

I am working with the Yii2 basic template. In layouts/main.php, in the head section, I have set

<link rel="shortcut icon" href="<?php echo Yii::$app->getHomeUrl(); ?>/favicon.ico" type="image/x-icon" />

or

<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />

or ... (so on), but anything seems to work. My application keeps on showing the basic template favicon instead of mine, that is in the root web folder as usual.

I know I could publish this file to avoid this problem, but I think there should be no need.

What am I doing wrong? And how does Yii2 displays its standard favicon anyway?

Upvotes: 13

Views: 25658

Answers (6)

Serghei Leonenco
Serghei Leonenco

Reputation: 3517

You can do this as simple as adding an extra line to your AppAsset.php file:

public $css = [
        [
            'href' => 'path-to-your-icon/icon-32x32.png',
            'rel' => 'icon',
            'sizes' => '32x32',
        ],
        [
            'href' => 'path-to-your-icon/icon-192x192.png',
            'rel' => 'icon',
            'sizes' => '192x192',
        ],
        [
            'href' => 'path-to-your-icon/icon-180x180.png',
            'rel' => 'apple-touch-icon-precomposed',
        ],
        'css/site.css',        
    ];

Hope it will helps.

Upvotes: 6

ersks
ersks

Reputation: 1499

Step 1 : Define common parameter in (common/config/params.php) as below:

return [
    'adminEmail' => '[email protected]',
    'supportEmail' => '[email protected]',
    'user.passwordResetTokenExpire' => 3600,    
    'commonPath' => '/<your_project_name>/common',
];

Step 2 : Use defined commonPath to display favicon icon as follows:

<link rel="shortcut icon" href="<?= Yii::$app->params['commonPath']; ?>/favicon.ico" type="image/x-icon" />

Note: Place your favicon.ico in common/ directory.

Upvotes: 0

johnsnails
johnsnails

Reputation: 2031

Another way to set the favicon as described in the documentaion is by adding something like this to the main.php file located under views/layouts. $this->registerLinkTag(['rel' => 'icon', 'type' => 'image/png', 'href' => '/favicon.png']);

Upvotes: 13

zahrin
zahrin

Reputation: 11

instead of using :

Yii::$app->request->baseUrl;

try using :

Yii::$app->assetManager->getPublishedUrl('@frontend/assets/dist')

Upvotes: 0

temirbek
temirbek

Reputation: 1452

as rkm mentioned it's because of browser cache. Easy fix is to add version like ../favicon.ico?v=1 and browser will load new version.

Upvotes: 7

ScaisEdge
ScaisEdge

Reputation: 133410

I have the favicon.ico in app/web directory and the code below is working properly

 <link rel="shortcut icon" href="<?php echo Yii::$app->request->baseUrl; ?>/favicon.ico" type="image/x-icon" />

Upvotes: 2

Related Questions