简体   繁体   中英

CakePHP adding image to echo $this->Html->link

Hi I have tried various things but not sure if I am trying to over complicate things. Quite simply I want to add a small image country flag for the word 'Spanish' and 'English' and have an 'Alt' tag with those words instead. The following works fine with just text and as is but it would be cool to have the image either to replace or sit side by side with the word. Any help available?

    echo $this->Html->link('Spanish', array('controller'=>'settings', 'action'=>'lang', 'spa'),
        array('rel'=>'nofollow'));
}

else {
    echo $this->Html->link('English', array('controller'=>'settings', 'action'=>'lang', 'eng'),
        array('rel'=>'nofollow'));
}

You can either output just a linked image using the image method with a url attribute:-

<?php

echo $this->Html->image(
    'spain.jpg', 
    array(
        'alt' => 'Spanish',
        'url' => array('controller' => 'settings', 'action' => 'lang', 'spa')
    )
);

Or you can include an image with a text link by combining the normal CakePHP link method and the image method:-

<?php

echo $this->Html->link(
    h('Spanish') . $this->Html->image('spain.jpg', array('alt' => 'Spanish')),
    array('controller' => 'settings', 'action' => 'lang', 'spa'),
    array('escape' => false, 'rel' => 'nofollow')
);

With the link method you need to remember to prevent Cake from escaping the img tag using 'escape' => false . If you disable escaping like this it is work remembering to escape any user provided text by using the h() method to prevent any HTML injection (I've shown this in my example wrapping the word 'Spanish' but this is only necessary if this is coming from a variable).

if you are using cake2 see this link to the cookbook

echo $this->Html->image("spain.jpg", array(
    "alt" => "Spanish language",
    'url' => array('controller' => 'settings', 'action' => 'lang', 'spa')
));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM