Problem in CSS and JS path in MVC project

3

I'm building a php application with MVC, the problem is when accessing other directories through the URL, eg: mvc / user now: mvc / user / create (here the sheet of css styles and javascript are no longer found), what is the best way to fix this? to set 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

Very simple.

    
asked by anonymous 06.04.2014 / 02:33

4 answers

3

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

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

Ideally, you should not use relative paths to 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 root of the site, not the address that is in the browser's address bar.

    
06.04.2014 / 03:03
1

I do not know if you're familiar with the View Helpers concept, otherwise, take a look around.

What I usually do is create a helper that helps me resolve the paths to these assets:

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

In some configuration file I do this:

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

This way you are not dependent on a directory hierarchy.

    
06.04.2014 / 15:12
0

Let's assume that this is the structure of your site:

/principal
  /css
  /img
  /js
/blog

If you want to load a style sheet from the blog directory, simply load it as follows:

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

However, if someone is in the directory blog / 05/04/04, this URL will point to: blog / 05/04/2013 / main / css and this is not the directory we want. To load independent of any directory (if the main directory and blog are in the root of the site) simply 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 to your tag script and be happy.

    
06.04.2014 / 04:37
0

Defining a constant, ideally, you 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 because it suits all your files, css, images, serves for MVC and rewrites.

    
06.04.2014 / 20:20