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

My Syntax:
<?php echo $html->link('CakePHP Book', ''); ?>

And output:
 <a href="">CakePHP Book</a>

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', '', 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', '', 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', '', 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">

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


I have not used the complete path to about us page, which is:
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 {

That's it.
Here is a preview:

That's it.



john said...

thanks man, it works excellent....

john said...

thanks man! it works excellent...

Siddhartha said...

Thanks a lot John!