How to Use CHtml to Add MetaTag to Static Pages

I want to add metaTags to the static pages but am confused on how to accomplish it.

I have found the Yii documention for the metaTag()method

"Generates a meta tag that can be inserted in the head

section of HTML page."… That sounds good but I am not sure how to implement it. Controller, or on the static page.

I tried adding it to the static page


<?php

$this->pageTitle=Yii::app()->name . ' - My Page Title';


echo CHtml::metaTag($content='My page description', $name='decription');


$this->breadcrumbs=array(

	'Site Page',

);

?>

… but do not get a tag when I view the page source. No surprise.

If I add it to the controller then how would the page descriptions be unique for each static page?

I really need some guidance!

Something like this:





<?php

/**

 * Controller is the customized base controller class.

 * All controller classes for this application should extend from this base class.

 */

class ExtendedController extends CController

{


    public function render($view, $data = null, $return = false)

    {

        if ($this->beforeRender($view))

        {

            parent::render($view, $data, $return);

        }

    }


    public function beforeRender($view)

    {

        return true;

    }


}






<?php

/**

 * Controller is the customized base controller class.

 * All controller classes for this application should extend from this base class.

 */

class Controller extends ExtendedController {


    /**

 	* @var string the default layout for the controller view. Defaults to '//layouts/column1',

 	* meaning using a single column layout. See 'protected/views/layouts/column1.php'.

 	*/

    public $layout = '//layouts/column1';

    /**

 	* @var array context menu items. This property will be assigned to {@link CMenu::items}.

 	*/

    public $menu = array();

    /**

 	* @var array the breadcrumbs of the current page. The value of this property will

 	* be assigned to {@link CBreadcrumbs::links}. Please refer to {@link CBreadcrumbs::links}

 	* for more details on how to specify this property.

 	*/

    public $breadcrumbs = array();


    public $pageTitle;

    public $pageKeywords;


    public $pageDescription;


    public function beforeRender($view) {


        $this->pageTitle = Yii::app()->params['title'] . ' ' . Yii::app()->params['description'];


        if (!empty($this->pageDescription)) {

            Yii::app()->clientScript->registerMetaTag($this->pageDescription, 'description');

        } elseif(empty($this->pageDescription)) {

    	$this->pageDescription = Yii::app()->config->get('meta_description');

            Yii::app()->clientScript->registerMetaTag($this->pageDescription, 'description');

        }

        if (!empty($this->pageKeywords)) {

            Yii::app()->clientScript->registerMetaTag($this->pageKeywords, 'keywords');

        } elseif(empty($this->pageKeywords)) {

            Yii::app()->clientScript->registerMetaTag(Yii::app()->config->get('site_keywords'), 'keywords');

        }


        return true;

    }


}

And how do you set the metatag?

Same as you would set the other controller variables, like menu, breadcrumbs, etc - in the views.

Thanks jacmoe.

After posting my questions I decided to get some sleep and as I started to doze off It occurred to me that I would probably need to set the variables in the controller.

I have come across class files like this … http://code.google.com/p/yii/source/browse/tags/1.1.9/framework/web/helpers/CHtml.php#189 … when searching different things, but I was under the impression that those pages were describing classes that were already set in the framework ready to use. ‘Ready to use’ is a bit clearer to me now. Ready to use in a controller to set the variables, not ready to use on a view page.

Anyway,

The code you offered, which I have seen at this link …

http://www.yiiframework.com/wiki/54/simplified-meta-tags/ … is starting to make a little more sense now. I thought that code was for the dynamic pages, not static pages.

Still, I am a bit confused on the subject of controllers.

My framework has ready this - class SiteController extends Controller.

  • Controller is the customized base controller class.

  • All controller classes for this application should extend from this base class, yet…

The code you offered and the code offered at the simplified-meta-tag link reffer to - class ExtendedCController extends CController.

How does CController tie in? What does the C in CController mean? I can’t find CController in my files.

CController is the Yii framework class.

The ‘C’ prefix is reserved for Yii classes.

If it didn’t inherit it, how would it be a controller? :)

If I am following this correctly then…

  1. I need to create the ExtendedController.php, with render and beforeRender functions, in my components folder. and now it extends CController.

  2. Change my Controller…

FROM: class Controller extends CController

TO: class Controller extends ExtendedController - and add all the new variables along with the beforeRender function.

Yes?

I tried it and got CException - Property "CWebApplication.config" is not defined.

So,… was i wromg in trying it this way or what?

To be more specific this is the Stack Trace…

.../protected/components/Controller.php(36): CModule->__get("config")




36         $this->pageDescription = Yii::app()->config->get('meta_description');

You don’t need this. beforeRender() is implemented in the latest Yii versions. Just extend all your controllers from Controller (which contains the meta tag logic).

That means the there is no "config" component defined in your config.

Thanks Yii, but I am still confused about this; There needs to be a ‘config’ component defined in the ‘config file’?

Looking through the CWebApplication link,

http://www.yiiframework.com/doc/api/1.1/CWebApplication , I do not see reference to a ‘config’ property or one that appears relevant to config.

However I do see a ‘components’ property plus I noticed a config array being used in your code found in your signature link Extension:Config. Is this what my main.php config file is missing…




// application components

		'components'=>array(

			.....


			'config'=> array(

				'class'=>'XYZ'),

			.....



I am trying to understand what about config that needs to be defined but the documentation isn’t helping to answer the question.

By reasoning that the CException is at line 26 - config->get(‘meta_description’) … Does the config array need to define the getting of the meta tag?

Am I even looking in the right direction? Hot, cold, warm?

Well in this case it means you do not have the config extension installed.

For the beginning you can use the params property of CWebApplication. In your config file you can do:




// Make sure it's NOT in 'components' array

'params' => array(

   'meta_description' => 'Some description',

),



And then:


$this->pageDescription = Yii::app()->params['meta_description'];

That should work flawless. Now go to the extension page of the config extension and follow the instructions on how to install.

Well, yes :)

:HandsOnHips: Well, why didn’t you tell me that before?!? :rolleyes:

So,…

  1. The code presented at the Simplified Meta Tags link IS NOT for the static pages. http://www.yiiframework.com/wiki/54/simplified-meta-tags/

  2. A generic meta tag can be set using params which displays the same meta content for every page-view, site-wide.

  3. By setting params for static pages meta tags, and using the Simplified Meta Tags code for dynamic pages meta tags, the result is that the dynamic pages will get two meta tags, one from each source.

  4. To get a single, unique meta tag for each type of page then the extension needs to be implemented.

It is my understaning that the extension is for storing the meta tag content in a database then calling it for the appropriate page…

Is there anything else you could tell me, now?

You want to store meta tags in database for the index page. This way you can change the meta tags like the title from the admin backend for various reasons. Of course you could add more config options like ‘moduleName_title’, then you could change the meta title of each module’s index page in the admin backend. Or you could even add tags for every controller and action.

If the tags are not from database, then simply set them in each controller/action. You can also set defaults by simply defining the values in the base controller (Controller.php).




public $pageTitle = 'Some title';



If you want defaults to be loaded from database:


class Controller extends CController

{


   public function init()

   {

      parent::init();

      $this->pageTitle = Yii::app()->config->get('meta_title');

   }


}

There’s not much sense in using config extension & params at the same time I guess. Just use one or the other and set “dynamic” meta tags within the controller.

Your extension looks a bit much for my simple site, however you did make me think of something I hadn’t thought of; searching the yii framework for an available extension! :headThump: thump you and jacmoe too for not suggesting it in the first place!

I found one that even I could implement, without help! It’s working well on both types of pages. There are parts of it that I am not using, however I might use the full features later.

SEO - Developed by: Chris83

http://www.yiiframework.com/extension/seo

What’s included?

SeoRecordBehavior - Active record behavior for defining the model URL


SeoControllerBehavior - Controller behavior for setting page meta data


SeoFilter - Controller filter for correcting incorrect URLs


SeoMetaWidget - Widget for rendering page meta data

THANK YOU CHRIS!

…and thank you Yii, I do appreciate your time, you have given me alot to think about.