0

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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

How can be justified modifying the template or extending the HTML helper instead of of just using this directly?: <img class="lazy" data-src="<?php echo $imageUrl;?>" />. Security, scalability,...? What would be the main benefit of "doing it the CakePHP way"? It looks straightforward to simply use pure PHP/HTML code: <img class="lazy" data-src="<?php echo $imageUrl;?>" />.
@JaimeMontoya The main benefit is the underlying path management, ie the helper will create the correct path irrespectively of your applications base path, it supports theme assets, and timestamping. Also using standard CakePHP code makes refactoring easier.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.