Chad 2010-05-31
In Symfony 1.4, we can use the view.yml to configure html meta tags:
- // config/view.yml
- default:
- metas:
- title: My Website
- description: This is Chad's website
- keywords: Chad, website, php, symfony
- #language: en
- #robots: index, follow
And we can also override the meta values in Symfony actions:
- // apps/someApp/modules/someModule/actions/actions.class.php
- public function executeIndex(sfWebRequest $request){
- $this->getResponse()->addMeta('title', 'custom title');
- // $this->getResponse()->setTitle('custom title') would do the same job as above
- }
Then if we use the include_metas() and include_title() method at the same time, both of the code above would generate two meta tags for the "title":
- // html output
- <html>
- <head>
- <meta name="title" content="My Website" />
- <title>My Website</title>
- ...
Is this possible to have only the title tag and remove the other (the meta name="title" tag is not recognize by browsers anyway)? The answer is yes, and there are a lot of solutions. I think the best way is to subclass the sfWebResponse class and override the getMetas() method:
- // lib/myWebResponse.class.php
- class myWebResponse extends sfWebResponse
- {
- public function getMetas()
- {
- $metas = parent::getMetas();
- if(array_key_exists('title',$metas)){
- unset($metas['title']);
- }
- return $metas;
- }
- }
The code above would remove the the meta name="title" tag and keep the title tag. That's because the include_metas() and include_title() method use different way to generate the tags:
- // lib/vendor/symfony/lib/helper/AssetHelper.php
- function include_metas()
- {
- $context = sfContext::getInstance();
- $i18n = sfConfig::get('sf_i18n') ? $context->getI18N() : null;
- foreach ($context->getResponse()->getMetas() as $name => $content)
- {
- echo tag('meta', array('name' => $name, 'content' => null === $i18n ? $content : $i18n->__($content)))."\n";
- }
- }
- function include_title()
- {
- $title = sfContext::getInstance()->getResponse()->getTitle();
- echo content_tag('title', $title)."\n";
- }
Obviousely the include_metas() is using sfWebResponse::getMetas(), and include_title() using sfWebResponse::getTitle() to get the values set in the configuration file. Let's have a closer look at these two methods:
- // lib/vendor/symfony/lib/response/sfWebResponse.class.php
- public function getMetas()
- {
- return $this->metas;
- }
- public function getTitle()
- {
- return isset($this->metas['title']) ? $this->metas['title'] : '';
- }
It's quite clear that these two methods are actually retrieving values from the same array, so it's quite safe to override the sfWebRespose::getMetas() method to let include_metas() exclude the unwanted meta name="title" tag.