Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace a meta tag in Yii?

Tags:

meta-tags

yii

I know that I can register a new meta tag in Yii and I know how to do it, but I need to

replace the default tag that I have set, because when I am on a article, I want to insert the

short description of the article in the meta tag;

How can I manage the meta tags?

like image 786
Ionut Flavius Pogacian Avatar asked Feb 19 '13 07:02

Ionut Flavius Pogacian


3 Answers

If you're on the latest version you can give the metatag an id.

->registerMetaTag('example', 'description', null, array(), 'mytagid');

Calling registerMetaTag again with the same id will overwrite it.

http://www.yiiframework.com/doc/api/1.1/CClientScript#registerMetaTag-detail

like image 140
Alex Avatar answered Sep 18 '22 12:09

Alex


You can set Meta tag per page using:

Yii::app()->clientScript->registerMetaTag("This is my meta description", 'description');
Yii::app()->clientScript->registerMetaTag("These, are, my, keywords", 'keywords');

This can be set in the Controller or the view, and obviously depending on how you are querying your articles, you can make the content part dynamic like so (assuming $model is your selected article and meta_description is your model attribute storing the meta description):

Yii::app()->clientScript->registerMetaTag($model->meta_description, 'description');

Documentation on the Yii site can be found here

like image 26
Brett Gregson Avatar answered Sep 19 '22 12:09

Brett Gregson


You can try this:

1) In 'components/Controller.php':

public $metaDescription;
public $metaKeywords;

public function getMetaDescription() {
    if(!$this->metaDescription)
        return Yii::app()->settings->getValue('meta_description'); //return default description
    return $this->metaDescription;
}

public function getMetaKeywords() {
    if(!$this->metaKeywords)
        return Yii::app()->settings->getValue('meta_keywords'); //return default keywords   
    return $this->metaKeywords; 
}

2) In your main.php layout:

...
Yii::app()->clientScript->registerMetaTag($this->getMetaDescription(), 'description');
Yii::app()->clientScript->registerMetaTag($this->getMetaKeywords(), 'keywords');
...

3) In your other layouts:

...
// If you don't do that, the description and keywords will be default for this page.
$this->metaDescription = 'Your description here';
$this->metaKeywords = 'your, keywords, here';
...

Note, that Yii::app()->settings->getValue('meta_description') and Yii::app()->settings->getValue('meta_keywords') is my default values that takes from DB.

like image 36
Footniko Avatar answered Sep 18 '22 12:09

Footniko