Best way to load public assets in Slim 3 with different route configuration

I want to know how best to load my asset files with different route configuration.


With this route

$app->map(['POST', 'GET'], '/dashboard','AuthController:signIn') - my assets loads very well but on another configuration like

$app->map(['POST', 'GET'], '/editrecipe/{id}', 'AuthController:editUser'); all my css, javascript and images fail to load except if I add an extra dot.

I use php-view to render my templates.

The problem I am guessing is you need to reference your assets absolutely and not relatively.

ie all assets start with /

The following are actually very different.
assets/css/app.css (Relative to your current URI) #1
/assets/css/app.css (Absolute to your current URI) #2

With #1… if you are on page /mypage/1
The browser will attempt to load your assets at… /mypage/1/assets/css/app.css which will result in a 404.
Instead you want to prefix your assets with a / to tell the browser to look for the assets at the root of the site.

This works fine if you are running your application from your webroot. If like me, you have lots of subdirectories (one for each project) then you can use the following construct to ensure that you’re using an absolute path to reference your assets:

<link rel="stylesheet" type="text/css" href="{{ base_url() }}/css/style.css" />

Like this you don’t have to care which directory you’re running your project from.


Thanks, I can’t still make it to work except if I am using relative path but the problem still remains when I send GET request with parameter append to url.

The I would think you’re making some soft of a trivial mistake somewhere along the line, the code I posted above has worked well for me on several projects.

1 Like

To add to this. I think base_url() changes from one location to another. It’s ideal to make it this way if you are using a template layout. That way you insert it once from the main file. Otherwise, if you are inserting it on each file I am sure it will misbehave when your routes change. It may be working with /home and not with /user/{id}

But for other assets, like images. It’s ideal you go for relative path.

I have in my Slim project the directory src/images/ and I run my server at http://localhost:8080/. I’m building a React App and I’m trying display images from server in img tag <img src={ 'http://localhost/( path to image )' }. What is the relative path to my src/images/ directory of Slim project, getting through URL in browser?