Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CHtml::link - how to add a html class?

Tags:

yii

On docs we can read:

public static string link(string $text, mixed $url='#', array $htmlOptions=array ( ))

Question: I don't understand what $htmlOptions means here. I don't understand how to pass from this representation to a real code.

Can anyone please provide an example about how can we generate a link with a class defined. Something like:

<a href="#" class="hello">link hello</a>
like image 944
MEM Avatar asked Dec 09 '11 15:12

MEM


2 Answers

It's easier than you might think, although Yii's documentation is perhaps a bit more convoluted than needs to be. However, it does say that $htmlOptions is

additional HTML attributes. Besides normal HTML attributes, a few special attributes are also recognized (see clientChange and tag for more details.)

In essence, whatever key/value pairs you put into the array will come out as HTML attributes¹. So, what you want to do is

CHtml::link('link hello', '#', array('class' => 'hello'));

¹except the "special" values that the docs refer to, which will not end up rendered in HTML as-is but either modify the way link works slightly, or end up affecting the HTML in other ways.

like image 135
Jon Avatar answered Sep 17 '22 01:09

Jon


<?php echo CHtml::link('Link Text',array('controller/action','param1'=>'value1'), array('target'=>'_blank','class'=>'hello'); ?>

It will be shown as below.

<!--if you disabled url manager in "protected/config/main.php" the output will be -->
<a target="_blank" class="hello" href="index.php?r=controller/action&param1=value1">Link Text</a>

<!--if you enabled url manager in "protected/config/main.php" the output will be -->
<a target="_blank" class="hello" href="controller/action/param1/value1">Link Text</a>

To get a detailed description about CHtml in yii Check this link.

like image 24
Mahendran Sakkarai Avatar answered Sep 17 '22 01:09

Mahendran Sakkarai