Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic page titles in Symfony 1.4

I'm wondering if anyone's got any good advice/experience regarding setting dynamic meta titles in Symfony?

Currently, the solution I'm aware of would be to use the following code to set a title individidually in each action:

$this->getResponse()->setTitle('This is a title');

Because I also need translated titles, I could call the i18n helper in the action to get them included in the extracted XLIFFs. No special SEO stuff needed, just a clean title.

However, the above does require that I tweak every single action separately. View.yml is not suitable as I frequently have multiple actions/templates per module.

Is anyone aware of a better approach in Symfony or is this indeed the right/only way to go?

Thank you.

like image 538
Tom Avatar asked Apr 27 '10 14:04

Tom


4 Answers

You should use slots.

In your layout <head> tag:

<title><?php echo get_slot('page_title', __('Default page title here')) ?></title>

And in an action template:

<?php slot('page_title', __('Action page title goes here')) ?>
like image 167
NiKo Avatar answered Oct 21 '22 01:10

NiKo


I think writing separate titles in every action is OK. But if you want to add some global prefix you can use something like this in layout:

<title>SITE NAME — <?= $sf_response->getTitle() ?></title>

Also you can probably manipulate a title per module using preExecute() method in actions.

like image 35
zergu Avatar answered Oct 21 '22 01:10

zergu


I personally like using the yml files, it separates 'configuration' from code

To deal with dynamic titles I do the follow:

in apps/frontend/config/app.yml

all:
  title_separator: ' - '
  title_default: 'TITLE'

in apps/frontend/config/view.yml

default:
  metas:
    title: %APP_TITLE_DEFAULT%

If you need to have data from your actions put into the title, create file lib/myActions.class.php with the following content:

<?php

class myActions extends sfActions
{

    protected function setTitle($string)
    {
        $this->getResponse()->setTitle($string . sfConfig::get('app_title_separator') . sfConfig::get('app_title_default'));
    }

}

?>

(note: modify this as you like, e.g. put default title at front)

Then change your action.class.php to extend myActions instead of sfActions

class memberActions extends myActions

and whenever you need to change the title, just call this in your action

$this->setTitle('This is how I roll');

and you will get the following title (if using the same config as I did above):

This is how I roll - TITLE
like image 45
Populus Avatar answered Oct 21 '22 00:10

Populus


$i18n = $this->getContext()->getI18N();
$this->getResponse()->setTitle('Your title' . ' | ' . $i18n->__('your module name'));
like image 1
user9081752 Avatar answered Oct 21 '22 02:10

user9081752