CHtml, what is it good for?

Some of the functions in the CHtml class are handy, but isn’t it a waste of resources to write:




<?=CHtml::tag('div',array('id' => 'someId'))?>

    <?=CHtml::link('Label','http://example.com'?>

<?=CHtml::closeTag('div')?>



Instead of




<div>

    <a href="http://example.com">Label</a>

</div>



Which looks nicer, and is easier to read.

Where is the benefit of using those functions?

One of the things i do like about the CHtml class, is the errorSummary function. I wonder if theres a way to pass all models available to it. In order to collect all user errors in one place. Maybe using the register pattern by letting all models registering themselves. Does Yii has such a class?

CHtml wasn’t intended for replacing static HTML.

It’s for generating parametrized dynamic output.

Okay, but in the example blog, they use it quite a lot…

When to use and when to not use it?

Depends on you. ;)

Use it as you think it is appropriate. For example, I would use html for this:




<div>

  <a href="http://example.com">Label</a>

</div>



But I wouldn’t write this:




<div class="<?php echo $divClass; ?>" style="<?php echo $userAppliedAdditionalStyle; ?>">

  <a href="<?php echo $url; ?>" target="<?php echo $target; ?>"><?php echo Yii::t('ctxt', 'Label'); ?></a>

</div>



In such a scenario it might be better to wirte:




<?php

//prepare parameter arrays. Maybe this can be done in controller or model,

//whereas the html output might be done in the view.

[...]


//output html

echo CHtml::openTag('div', $aDivParams));

echo CHtml::link($label, $url, $aLinkParams);

echo CHtml::closeTag('div');

?>



Except that a model should never be coupled to a view, of course.




<?=CHtml::tag('div',array('id' => 'someId'))?>

    <?=CHtml::link('Label','http://example.com'?>

<?=CHtml::closeTag('div')?>



This is probably not a very good example of what CHtml is good for. In most cases it makes no sense in using the CHtml class to generate HTML Tags.

It is probably also very useful to generate external links.

For internal links, however it is very useful.

Consider the following example:

You have a Site controller that contains a login action.

In your Routes you’ve then defined /login to point to /site/login

When you generate the link using


 <?=CHtml::link('Label',array('site/login'))?>

Yii will automatically consider that route and change the link to just /login

For internal links, Yii will also prepend the base url, which is very useful if your application may not be installed in the domain’s root directory.

The CHtml class is also very useful for forms, because it will automatically preset the correct values in input fields and mark the input fields with a special CSS error class in case there were any validation errors.

hope that helps a bit

Marc