You’re writing a module that also has some necessary CSS or JS or images (or whatever) external media assets. How do you include them?
Here’s a strategy that lets you package a module with default CSS/JS/images, but still lets you override any of them for specific applications.
Let’s say you have a module structure like this:
modules/ +---- mymodule/ +-------- classes/ +------------ mymodule.php +-------- assets/ +------------ css/ +---------------- test.css
Step #1: Modify your .htaccess file
There’s a line in your .htaccess file that prevents module files from being loaded directly. We need to change it from:
# Protect application and system files from being viewed RewriteRule ^(?:application|modules|system)b.* index.php/$0 [L]
to this:
# Protect application and system files from being viewed
RewriteCond %{REQUEST_FILENAME} !.(css|js|jpg|png|gif)$
RewriteRule ^(?:application|modules|system)b.* index.php/$0 [L]
Step #2: Include the asset file in your view
Include the file using this type of format:
<html>
<head>
<link type="text/css" href="<?php echo URL::site( substr( Kohana::find_file('assets','css/test','css'), strlen(DOCROOT) ) ) ?>" rel="stylesheet" media="screen" />
</head>
<body>
</body>
</html>
The key here is the line:
substr( Kohana::find_file('assets','css/test','css'), strlen(DOCROOT) )
which uses Kohana’s built-in file searcher to get the path of the file, and then we substring out the document root, leaving the web path.
Note: this works for me on a linux/apache type config, but based on your server structure, you may need to edit this a bit.
Overriding the default module assets (Optional)
The nice thing about this approach is that it uses Kohana’s cascading filesystem, meaning that you can override the external media by placing a file with the same path structure.
For example, if you have some file modules/mymodule/assets/css/test.css:
body {
background: blue;
}
You can override the default file with your own by creating a file in application/assets/css/test.css:
body {
background: red;
}
Happy modding!