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
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';
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With