最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Laravel - Javascript can not find images when path changes - Stack Overflow

programmeradmin6浏览0评论

in my Laravel template I include a JS-file.

Here I am using a plugin which needs images.

    $.backstretch([
        "../img/header-tt-big.jpg",
        "../img/header-soccer-big.jpg"
    ]

So.. when I go to my "startpage" like this it is working: http://localhost/project/public/de/p1

When I go here it won't work http://localhost/project/public/de/p1/register

I would have to add another "../" for all images in the JS-file. How can I make this work without changing the array manually everytime?

Thank you :)

in my Laravel template I include a JS-file.

Here I am using a plugin which needs images.

    $.backstretch([
        "../img/header-tt-big.jpg",
        "../img/header-soccer-big.jpg"
    ]

So.. when I go to my "startpage" like this it is working: http://localhost/project/public/de/p1

When I go here it won't work http://localhost/project/public/de/p1/register

I would have to add another "../" for all images in the JS-file. How can I make this work without changing the array manually everytime?

Thank you :)

Share Improve this question asked Jan 19, 2015 at 15:37 gertigerti 1952 silver badges9 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 8

As @ITroubs pointed out, if you have the javascript code inside a blade template (<script> tag) you can and should use asset() to generate the URLs. But don't forget the extra quotes so javascript interprets it as string.

$.backstretch([
    "{{ asset('img/header-tt-big.jpg') }}",
    "{{ asset('img/header-soccer-big.jpg') }}"
]

However if you have the javascript code in separate .js files (which is actually remended) you can't do that. Instead I suggest you define a assetBaseUrl in your layout blade template before the javascript code that needs it:

<script>
    var assetBaseUrl = "{{ asset('') }}";
</script>

Usage:

$.backstretch([
    assetBaseUrl + "img/header-tt-big.jpg",
    assetBaseUrl + "img/header-soccer-big.jpg"
]

If you use blade then write the backstretch like this:

$.backstretch([
    "{{asset("img/header-tt-big.jpg")}}",
    "{{asset("img/header-soccer-big.jpg")}}"
]

Okay I added the script as inline in a script-tag. But i did put it in a seperate file like p1-inline.blade.php. So i can just include that one. Thank you ;)

发布评论

评论列表(0)

  1. 暂无评论