Reputation: 58014
I have a model called PageMetaData that contains a title and a description. This is to be tied to any other model and to be used as the title tag and meta description for the page.
So I have a model called Brand. Brand has a field called page_meta_data_id and Brand belongsTo PageMetaData
Now on the view for Brand I can run this code:
if(!empty($data['PageMetaData']['title']))
{
$this->set('title_for_layout', $data['PageMetaData']['title']);
}
else if(!empty($data['Brand']['name']))
{
$this->set('title_for_layout', $data['Brand']['name']);
}
if(!empty($data['PageMetaData']['description']))
{
echo $this->Html->meta('description', $data['PageMetaData']['description'],array('inline'=>false));
}
else if(!empty($data['Brand']['description']))
{
echo $this->Html->meta('description', $data['Brand']['description'],array('inline'=>false));
}
And if a PageMetaData has been associated to the current Brand and has a value for title, it will set that as the page title, otherwise if the brand has a field called name it will us that. Same for description.
The problem is I don't want to have to diplicate this code in every view for every model that uses PageMetaData.
I cannot figure out where I can abstract the code to, to avoid duplication.
I cannot put it in a Behavior or a Helper because you cannot set the title from either. I cannot put it in a Component because it cannot access the data found from the model.
Is there somewhere I can put this code for reuse?
Upvotes: 1
Views: 147
Reputation: 17987
Place the method in your AppModel
. I assume the method accepts an id
for it to return the appropriate data.
Place another method in your AppController's beforeRender
method. Pass the id
to this method; which in turn will call the method in AppModel
; setting title_for_layout
, meta_description
and keywords
.
You should also not echo out these values, but rather pass them to the view and output them there (or in the layout).
AppController and AppModels are application-wide; so any controller/model may access the methods.
I'm sure there's other methods; and this might not work as I haven't tested it.
Upvotes: 0
Reputation: 21449
You can possibly use elements for this. have a look at the cookbook link:
http://book.cakephp.org/view/1081/Elements
Upvotes: 1