Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

yii2 how to replace customize meta tag from "view" with default meta tags in "layout"

Tags:

html

php

yii2

I want to put default meta data description tag for main template layout.

There are many cases where I needed to replace the default meta tags like description and keywords with customize data in views.

I have tried:

$this->registerMetaTag

In views where I need to customize the meta tags and also I have used this in main layout.

I thought if I would use meta tags with their id or name it would be replaced but the result shows duplicate meta tags like e.g.

<meta id="main_index" name="Description" content="my default content added by layout.">


<meta id="main_index" name="Description" content="my customized content added by the view"></head>

What is the best way to provide default description tag but can be customize by views whenever I call $this->registerMetaTag

like image 316
wolvorinePk Avatar asked May 11 '15 15:05

wolvorinePk


1 Answers

Here's my solution which is much simpler without redundant controller. All you need is to define default tags in app params and overwrite them in view.

config/params.php

<?php
return [
    'adminEmail' => '[email protected]',
    'og_title' => ['property' => 'og:title', 'content' => 'title'],
    'og_description' => ['property' => 'og:description', 'content' => 'description'],
    'og_url' => ['property' => 'og:url', 'content' => '/'],
    'og_image' => ['property' => 'og:image', 'content' => 'image']
];

views/layouts/main.php

<?php
    $this->registerMetaTag(Yii::$app->params['og_title'], 'og_title');
    $this->registerMetaTag(Yii::$app->params['og_description'], 'og_description');
    $this->registerMetaTag(Yii::$app->params['og_url'], 'og_url');
    $this->registerMetaTag(Yii::$app->params['og_image'], 'og_image');
?>

Now if I need to set custom tags I overwrite params in my view

views/site/index.php

<?php
    Yii::$app->params['og_title']['content'] = 'custom title';
    Yii::$app->params['og_description']['content'] = 'custom desc';
    Yii::$app->params['og_url']['content'] = '/new/url';
    Yii::$app->params['og_image']['content'] = 'image.jpg';
?>
like image 127
leealex Avatar answered Sep 27 '22 19:09

leealex