wolvorinePk wolvorinePk - 26 days ago 12
PHP Question

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

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

Answer

I made it my self , since my objective was not to repeat on each action a default keywords or other meta tags, but places where i would like to replace i would use registerMetaTag in action.

  • First create your own extended version of Controller like below

    class MyController extends Controller
    {    
        public function beforeAction($event){
        $this->view->title = Yii::$app->params['pageTitle'];
    
        \Yii::$app->view->registerMetaTag(Yii::$app->params['pageDefaultDescription'],"default_description");
        \Yii::$app->view->registerMetaTag(Yii::$app->params['pageDefaultKeywords'],"default_keywords");
        \Yii::$app->view->registerMetaTag(Yii::$app->params['pageDefaultAuthor'],"default_author");
    
        // Open Graph Tags
        \Yii::$app->view->registerMetaTag(Yii::$app->params['pageDefaultOG_Description'],"default_og_description");
        \Yii::$app->view->registerMetaTag(Yii::$app->params['pageDefaultOG_SiteName'],"default_og_sitename");
        \Yii::$app->view->registerMetaTag(Yii::$app->params['pageDefaultOG_Title'],"default_og_title");
        \Yii::$app->view->registerMetaTag(Yii::$app->params['pageDefaultOG_Type'],"default_og_type");
    
    
        return parent::beforeAction($event);
        }
    } 
    
  • So now all the customized keywords author etc meta tags can be added from the config file of param as a default.

  • Now any new controller you create just extend that with MyController so by default all the above meta tags will be attached.

  • If you need to replace the meta tag or customize in some actions then do like below.

     public function actionIndex()
    {
    
    
        \Yii::$app->view->registerMetaTag([
            'name' => 'description',
            'content' => 'my customize description for the index.',
            'id'=>"main_index"
        ],"main_index"); //this will now replace the default one.
    
    
        return $this->render('index');
    }
    
Comments