wolvorinePk wolvorinePk - 1 year ago 289
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:


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

Answer Source

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'];
        // Open Graph Tags
        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()
            'name' => 'description',
            'content' => 'my customize description for the index.',
        ],"main_index"); //this will now replace the default one.
        return $this->render('index');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download