简体   繁体   中英

Correct path for images in javascript using Cakephp

I am new in cakephp, and I have a script, which I converted to cakephp. I have there a rotate background that use 4 images like this:

$.backstretch([
    "img/bg/1.jpg",
    "img/bg/2.jpg",
    "img/bg/3.jpg",
    "img/bg/4.jpg"
], {
     fade: 1000,
     duration: 8000
});

When I open script like name_domain.com with use controller users and action login, it see all that images and all work perfect, but when I try to use register (controller=>users, action=>signup) the images are not load. But I put ../img.... then is working here and not in index.

How can I link correctly those images. I also try with "/img" but not working.

Any help will be appreciated.

try to use full path something like this.

$this->webroot.'img/myimage.jpg'

OR

$this->Html->url('/img/myimage.jpg')

OR

<?php Router::url('/img/myimage.jpg')?>

One method is to set a JavaScript variable, and then use that in your subsequent scripts. For example, in your app/Layouts/default.ctp file, you could have:

<script>
    var img_path = "<?php echo Configure::read('App.imageBaseUrl'); ?>";
</script>

And then use it in your scripts like this:

<script>
    $.backstretch([
        img_path + "/bg/1.jpg",
        img_path + "/bg/2.jpg",
        img_path + "/bg/3.jpg",
        img_path + "/bg/4.jpg"
    ], {
         fade: 1000,
         duration: 8000
    });
</script>

declare a javascript variable in default.ctp

var IMAGE_HOST = "<?php echo $this->webroot.'/img/'; ?>";

and now you can use it in javascript file too

<script>
$.backstretch([
    IMAGE_HOST + "bg/1.jpg",
    IMAGE_HOST + "bg/2.jpg",
    IMAGE_HOST + "bg/3.jpg",
    IMAGE_HOST + "bg/4.jpg"
], {
     fade: 1000,
     duration: 8000
});

hope it helps..!!

I would recommend to save webroot path in your layout so that its scope remain global

<div id="webroot" class="hide" data-url="<?php echo $this->webroot;?>"></div>

Then use it backstretch js as

 var webroot = $('#webroot').attr('data-url');
    $.backstretch([
        webroot+ "img/bg/1.jpg",
        webroot+ "img/bg/2.jpg",
        webroot+ "img/bg/3.jpg",
        webroot+ img/bg/4.jpg"
        ], {
          fade: 1000,
          duration: 8000
});

When you use different action having same layout with webroot element, it will keep the correct image path.

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