Why to use CHtml::link() and others?

Hi,

I had this question since the time I learned CHtml::link() and other similar functions in CHtml helper class. Is there a specific reason to use these functions? Is it because of some kind of security reason? Is it not better to use <a></a> tag and get the job done instead of using CHtml::link(), since it is easier? Same is the case with CHtml::encode() and other functions. Why can’t we simply place the required content in the view file instead of doing CHtml::encode() on the same?

I feel there is huge concept behind this and would certainly like to learn about it.

CHtml is just a helper class… it’s up to you if you want to use it or not…

Okay. So there is absolutely no advantage CHtml has and it makes no difference using HTML directly?

CHtml::link() allows to generate "href" attribute dynamically based on url rules. Without this method your link will look like:




<a href="<?php echo $this->createUrl('controller/action'); ?>">Link</a>



CHtml::encode() encodes special html chars. You don’t need to use it everywhere, but inside tags attributes it becomes helpful:




<a href="#" title="<?php echo $model->title; ?>">Link</a>



If $model->title contains double quotes, your html will be broken.

Makes sense.

So, in your link example, using CHtml it can be written as,


<?php echo CHtml::link('Link', array('controller/action')); ?>

Correct?

Exactly. Once you defined controller/action in the link, you won’t need to change it again when you want the url to look differently. Actually it is most useful when testing applications, because in production links change rarely (for SEO reasons).

The advantage is:

if you rout your site/login

to login.html

if all you website have simple links… you will have to go and change all…

if you use CHtml::link

you don’t need to change anything… just change the routing and it changes everywhere

Okay. Sounds good.

@dckurushin

You mean, if I add a new rule inside urlManager to route site/login to login.html?

Not just site/login of course… this is just an example

but yes, if you add route, it will automaticly change the links