Search code examples
phpfat-free-framework

Dynamic Routing not properly linking to CSS and JS files


I'm currently trying to set up a project in Fat-Free-Framework 3.6 - but I dislike the idea of having to manually add all my basic routes to routes.ini, and I decided I wanted to try my hand at more dynamic routes.

For this, I've made 2 new GET routes. Here is what I have:

$f3->route('GET /@module','{@module}_controller->index');
$f3->route('GET /@module/@method','{@module}_controller->@method');

The first one is to load a controller and it's default method (Which I have made index in these examples).

The first route works great, if I navigate my browser to http://example.com/ex1, it will load controller ex1_controller and run the index method, and everything will run and display properly.

The second route however, does not work as expected. When trying to run the exact same method within the second route, I get no CSS. For example, if I now navigate to http://example.com/ex1/index, there is no CSS on the page - but when I inspect the page source, I see the CSS should be loaded in as <link rel="stylesheet" type="text/css" href="assets/css/uikit.min.css"> is in the page.

Upon further investigation, I followed the link to the CSS file in my source code which brought me to the incorrect link. During the 2nd route, for some reason it's not trying to load from the root. It's trying to load from the URL ./ex1/assets/css/uikit.min.css, but the CSS actually exists in ./assets/css/uikit.min.css

Structure:

index.php - Where routes are defined
| app
    | controllers
        Controller.php
        ex1_controller.php
    | models
        ex1.php
    | views
        | ex1
            index.htm
| assets
    | css
        uikit.min.css
    | js
        uikit.min.js

ex1_controller.php

<?php

class ex1_controller extends Controller {

    function index() {

        $example = new ex1($this->db);

        $output = $example->returnOutput();

        $this->f3->set('output', $output);

        echo $this->template->render('ex1/index.htm');

    }
}

The Controller.php file is run on every route, which is then extended by the controller for the module. This is where the main_header.htm file is loaded in, which contains the css/js links. This is how the links are defined in main_header.htm;

<link rel="stylesheet" type="text/css" href="assets/css/uikit.min.css">
<script src="assets/js/uikit.min.js"></script>
<script src="assets/js/uikit-icons.min.js"></script>

Why is F3 trying to load CSS/JavaScript from the wrong directory when using dynamic routes such as this, and how can I fix it?


Solution

  • The fix for this seems to be quite easy.

    Simply add a slash to the beginning of the linked resource path.

    <link rel="stylesheet" type="text/css" href="/assets/css/uikit.min.css">
    <script src="/assets/js/uikit.min.js"></script>
    <script src="/assets/js/uikit-icons.min.js"></script>