Welcome to the Cookbook

loading...

7.4.1.6 image

image(string $path, array $htmlAttributes = array())

Creates a formatted image tag. The path supplied should be relative to /app/webroot/img/.

<?php echo $html->image('cake_logo.png', array('alt' => 'CakePHP'))?> 
  1. <?php echo $html->image('cake_logo.png', array('alt' => 'CakePHP'))?>

Will output:

<img src="/img/cake_logo.png" alt="CakePHP" /> 

To create an image link specify the link destination using the url option in $htmlAttributes.

<?php echo $html->image("recipes/6.jpg", array(
    "alt" => "Brownies",
    'url' => array('controller' => 'recipes', 'action' => 'view', 6)
)); ?>
  1. <?php echo $html->image("recipes/6.jpg", array(
  2. "alt" => "Brownies",
  3. 'url' => array('controller' => 'recipes', 'action' => 'view', 6)
  4. )); ?>

Will output:

<a href="/recipes/view/6">
    <img src="/img/recipes/6.jpg" alt="Brownies" />
</a>

You can also use this alternate method to create an image link, by assigning the image to a variable (e.g. $image), and passing it to $html->link() as the first argument:

    <?php
    $image = $html->image('recipes/6.jpg', array(
                'alt' => 'Brownies',
            ));

    //$image is passed as the first argument instead of link text
    echo $html->link($image, array(
            'controller' => 'recipies',
            'action' => 'view',
            6
            ),
            array(
                'escape' => false //important so htmlHelper doesn't escape you image link
            )
    );
    ?>
  1. <?php
  2. $image = $html->image('recipes/6.jpg', array(
  3. 'alt' => 'Brownies',
  4. ));
  5. //$image is passed as the first argument instead of link text
  6. echo $html->link($image, array(
  7. 'controller' => 'recipies',
  8. 'action' => 'view',
  9. 6
  10. ),
  11. array(
  12. 'escape' => false //important so htmlHelper doesn't escape you image link
  13. )
  14. );
  15. ?>

This is useful if you want to keep your link and image a bit more separate, or if you want to sneak some markup into your link. Be sure to pass 'escape' => false in the options array for $html->link($string, $url, $options) to prevent htmlHelper from escaping the code.