cakephplazy-loadingcakephp-1.2jquery-lazyload

Removing 'src' attribute from output of $html->image() in CakePHP


I am using CakePHP 1.2. I am trying to use jQuery Lazy (http://jquery.eisbehr.de/lazy/example_basic-usage) from CakePHP. Reading the documentation at https://book.cakephp.org/1.2/en/The-Manual/Core-Helpers/HTML.html#image, it shows how

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

produces the following output:

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

I need to produce this output:

<img class="lazy" data-src="/img/cake_logo.png" />

How can I do that using $html->image() in CakePHP 1.2? The problem is that in the syntax image(string $path, array $htmlAttributes = array()), the first parameter is mandatory and in the output it produces the src=... attribute of img. I need to have an output with <img... /> that does not contain the src=... attribute. How could I achieve that using $html->image() in CakePHP?


Solution

  • Via the built-in HTML helper it's not possible without modifying the tag template. So if you need lazy loading on all images, then you could for example change the image tag template to something like:

    <img class="lazy" data-src="%s" %s/>
    

    However this would clash with using the class attribute. So alternatively you could extend the HTML helper and implement a custom image() method (or an additional method). Here's a quick & dirty example, which should be pretty self-explantory:

    function image($path, $options = array())
    {
        $defaults = array(
            'class' => null
        );
        $options += $defaults;
    
        $options['class'] = 'lazy ' . $options['class'];
    
        $originalTemplate = $this->tags['image'];
        $this->tags['image'] = '<img data-src="%s" %s/>';
    
        $imageHtml = parent::image($path, $options);
    
        $this->tags['image'] = $originalTemplate;
    
        return $imageHtml;
    }
    

    See also