Problem in CSS and JS path in MVC project

Asked

Viewed 1,241 times

3

I am building a php application with MVC, the problem is when accessing other directories by URL, Ex: mvc/user (so far all right) now: mvc/user/create (here the css style sheet and javascript are no longer found) what is the best way to fix this? define a constant or configure htaccess?

Structure

-controllers/ 
-lib/ 
-public/ 
   --css/ 
   --js/ 
   --images/
-models/ 
-views/ 
   --Index/ 
   --Create/ ... 
   Header.phtml
   Footer.phtml

.htaccess

RewriteEngine On

RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^(.*)$ index.php?url=$1

All very simple.

  • 1

    Using some framework? Could you show how the directory structure is?

  • No, I’m doing the hand to study. here the structure: -controllers/ -lib/ -public/ --css/ --js/ --images/ -models/ -views/ --Index/ --Create/ ...

  • 1

    How is the . htaccess script that does the redirects? Edit your question with the answers you put here in the comments.

4 answers

3

You’re probably using relative paths to reference the CSS and JS files.

<link rel="stylesheet" href="css/file.css">

Ideally do not use relative paths for these files.

Example:

<link rel="shortcut icon" href="/css/file.css">

The bar at the beginning of the path to the CSS file above indicates that the path is relative to the site root, not to the address that is in the browser’s address bar.

1

I don’t know if you’re familiar with the concept of View Helpers, if not, do a search around.

What I usually do is create a helper that helps me solve the paths to these resources (Assets):

<link rel="stylesheet" type="text/css" href="<?= $this->asset('/css/file.css');">

In some configuration file I do so:

[view]
helpers.asset.base_dir=/path/to/assets

This way you won’t be dependent on a directory hierarchy.

0

Let’s assume that this is the structure of your website:

/principal
  /css
  /img
  /js
/blog

If you want to load a stylesheet from the blog directory, just load it as follows:

<link rel="stylesheet" href="principal/css/main.css" />

However, if someone is in the blog directory/05/04/2014 this URL will point to: blog/05/04/2013/main/css and this is not the directory we want. To load independent from any directory (if the main directory and blog are at the site root) just load as follows:

<link rel="stylesheet" href="/principal/css/main.css" />

Or in your case:

<link rel="stylesheet" href="/public/css/arquivo.css" />

Just apply this also in your script tag and be happy.

0

To define a constant, the ideal is to create a variable in your MVC configuration file, with a domain name for example and use this variable at the beginning of all your files. This is ideal in my opinion as it serves for all your files, css, images, serves for MVC and rewrites.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.