Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

How to set dynamic meta tag descriptions

Hi,

I am using a common view for all my pages. I would like to know how to set dynamic meta descriptions for each page? via the controller. This is how i do it for meta titles.

View

<html>
    <head>
        <?php echo \Phalcon\Tag::getTitle() ?>
        <?php $this->assets->outputCss() ?>
</head>

Controller

\Phalcon\Tag::setTitle('This is my title');

I realized that that is no setDescription in the tag class. What is the recommended and elegant way of doing it?

Are you opposed to simply using view variables? At this point, I've been using a simple ternary in my layout that says "if description is set, output it, otherwise, default to nothing or the value set in my config file (depending)". It may not be as elegant as if there was a setDescription method, but it works.

If that won't do, you could always extend the Phalcon tag class. Something like \MyNamespace\Tag::setDescription(). - That's the beauty of OOP :p.



10.4k

Hi Tyler, i just got started in phalcon. Is there any tutorials on how to extend phalcon class? Dont have an idea how to implement it..



6.4k
Accepted
answer
edited Nov '14

I am not aware of any tutorials on extending a Phalcon class. I am not sure how familiar you are with object-oriented programming or any of it's concepts, but extending a Phalcon class is no different then extending any other class.

class CustomTag extend \Phalcon\Tag {

    public function setDescription() {
        //.....
    }

}

Now CustomTag has all of the functionality that \Phalcon\Tag had - automatically. Now, anywhere in your code that you would have used \Phalcon\Tag, you simply utilize your class instead.

In addition, to wire it up in the Phalcon Dependency Injector, you would register it under the name tag. You can view default names for various classes here. You will also find info on registering your new tag class on that page if you are unfamiliar with that process.

As I said in my original response, there is also the option of using a view variable for your meta description. Whatever works for you.

That's a great answer Tyler Shaw, So, what name do you give to this file:

 class CustomTag extend \Phalcon\Tag {

     public function setDescription() {
         //.....
     }

 }

And which folder do you place it in? Any other changes to make it work? maybe the services file or something?



27.3k

Hi,

you can put that file where you want (saying app/library). Just register the directory : https://docs.phalconphp.com/en/latest/reference/loader.html#registering-directories