Having dynamic titles with TT

If you are starting with catalyst and with TT (toolkit template) you will probably want to have custom titles you your web pages.
Well you can say: "i can already do that i just go to my template and write something like":

[% META title = 'My custom title' -%]

Yes, you really wrote a custom title but in a while you might want something a little more 'custom' something like "Welcome foo!".

Ok that's easy, just add the user name to Catalyst stash and use it inside your template. So in your controller you can put:

$c->stash{user_name} = 'foo';

Fine now on the template:

[% META title = 'Welcome user_name' -%]

hmm that didn't work... :( Maybe a little of php:

[% META title = 'Welcome '.user_name -%]

naaaaaaaa ok ok, you got me.. :P (Note that the string concatination operator in TT is _ (undersroce) not . (dot))

So the trick is META is compile-time, you can't change in a real request, if you're using MyApp_server.pl -r you might see it changing once you reload your page but this is because you have the -r switch.
So the way to have this working is by doing a little trick by changing the META call.

The first thing to do is in you controller change/create a end method to you controller:

sub end {
    my ($self, $c) = @_;
    $c->stash(meta => {});

Change your TT to suits your needs:

[% meta.title = 'Welcome ' _ user_name -%]

Ok, now if you are using those templates from the tutorial, or you are using TTSite you will also need to change the site/header file from:

<h1 class="title">[% template.title or site.title %]</h1>


<h1 class="title">[% meta.title or site.title %]</h1>

Nice, now everything is working, well maybe not everything if you have another controller you'll find that the title is gone!

Yes, i know what you're thinking. You need to change all the others files. If you know sed you another command line word processor you can use it. Matthew S. Trout just came with this Perl command (use it if you are in a Unix environment and at the root of your application):

find root | xargs perl -pi -e 's/META title/meta.title/;'

That's it, just make sure you use the meta.title in your new templates.

My tags:
Popular tags:
Powered by Catalyst
Powered by MojoMojo Hosted by Shadowcat - Managed by Nordaaker