Wednesday, November 11, 2009

Creating HTML Text Links with CakePHP

So, we have just created our about_us page. Now we need to create a link to this page. CakePHP has defined its own class for you to create links. The basic syntax is simple.

<?php echo $html->link('Link Text', 'Link URL'); ?>

For example: I wanted to create a link to http://book.cakephp.org

My Syntax:
<?php echo $html->link('CakePHP Book', 'http://book.cakephp.org'); ?>

And output:
 <a href="http://book.cakephp.org">CakePHP Book</a>

Note:
1. To create a link you need to echo the entire statement.
2. You can change link to point to any path - even relative paths.
3. You can use additional attributes to mention CSS class

Let us add a CSS class to that link.
<p><?php echo $html->link('CakePHP Book', 'http://book.cakephp.org', array('class'=>'ext')); ?></p>

Note the part I have marked with red ink. This link is now associated with class 'ext'. (Do not forget to define the 'ext' class in your css, in my case it is cake.generic.css file). And you are done.

To open this link in a new window:
<?php echo $html->link('CakePHP Book', 'http://book.cakephp.org', array('class'=>'ext', 'target'=>'_blank')); ?>
Note I have added 'target'=>'_blank' to that statement.

To add a javascript confirmation box to that link:
<?php echo $html->link('CakePHP Book', 'http://book.cakephp.org', array('class'=>'ext', 'target'=>'_blank'), "Do you really want to visit this website?"); ?>

Note I have added just the string to display and nothing more. Cake takes care of the rest of the stuff efficiently. And there's really much more to explore!

In my CakeTest Application now I'll display a link in the footer section to 'about_us' page.

I'll edit default.ctp (found under 'app/views/layouts' and add the following lines (mark with red color).


<div id="footer">
<?php

echo $html->link('About us','about_us',array('class'=>'footer-link'));

?>
</div>


Note:
I have not used the complete path to about us page, which is:
/pages/about_us
You need to specify just that 'about_us' part in place of the 'link url'. Cake does the rest successfully.

Further, I'll add a new style to cake.generic.css file (found under 'app/webroot/css')


a.footer-link:link,a.footer-link:visited, a.footer-link:active {
color:#C1C1C1;
font-size:10px;
background-color:#ffffff;
text-decoration:none;
}
a.footer-link:hover{
color:#C1C1C1;
font-size:10px;
background-color:#ffffff;
text-decoration:underline;
}


That's it.
Here is a preview:














That's it.

Cheers!

3 comments:

John Jiménez said...

thanks man, it works excellent....

John Jiménez said...

thanks man! it works excellent...

Siddhartha said...

Thanks a lot John!