PHP: Rewriting paths for resources like CSS/JS
-
26-09-2019 - |
Question
I'm wondering if anyone knows of some tricks for rewriting the paths of web page resources, such as CSS and JS files.
Reason being; I'm working on a little CMS project in PHP, and I want to keep the different site components separated, such as templates, eg:
+- /
+- classes/
+- template.class.php
+- datasource.class.php
+- cache.class.php
+- templates/
+- admin.tpl.php
+- admin.dashboard.tpl.php
+- resources/
+- admin.css
+- admin.js
+- jquery.js
+- index.php
+- config.php
+- bootstrap.php
Most everything is called via bootstrap.php
, and the template.class.php
class is responsible for building templates out of files from /templates/
.
Anyways, should I just be using site-root relative paths for the CSS and other resources when creating the HTML template files? Or is there a more intuitive way of rewriting them that someone is familiar with? I've considered just regexing it all, but I'm curious to know what options are suggested.
Thanks :)
Solution
I'd suggest the template specify what CSS/JS files it needs (some syntax like use_javascript('jquery')
). Your template builder will inject the appropriate script
and link
tags into the head of the page. Then you can add other features like dependency resolution (use_javascript('jquery-ui', 'jquery')
) later on.
You can look at the REQUEST_URI and FILE/_DIR_ to figure out how to build a relative path to the resources, though generating an absolute path works fine too.