Created
August 20, 2014 20:23
-
-
Save brandonferens/877bde0948f4e52550e9 to your computer and use it in GitHub Desktop.
Load relative javascript assets based on route in Laravel
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function loadRelativeAssets() | |
{ | |
$routeArray = explode('.', Route::currentRouteName()); | |
// We take the current route, create an array form it, run it | |
// through the while statement checking to see if that file exists. | |
// If it does, we load it. Then we remove that last element | |
// from the array, and do it all again, until the array is empty | |
while (!empty($routeArray)) { | |
// Create the path to the js file | |
$path = 'js/' . implode('/', $routeArray) . '.js'; | |
// Create the asset name | |
$name = implode('', $routeArray); | |
// Check to see if the file exists within /public/js | |
if (File::exists(public_path() . '/' . $path)) { | |
// If the file exists, load it into Theme::asset() | |
Theme::asset()->container('footer')->add($name, $path); | |
} | |
// Remove the last element from the array | |
array_pop($routeArray); | |
} | |
} | |
loadRelativeAssets(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The whole idea for the above code is to dynamically and automatically load any assets based on the route.
For example, if your route is
admin.users.create
it will look forpublic/js/admin/users/create.js
,public/js/admin/users.js
, andpublic/js/admin.js
, and load them if it finds them.Line 18 references the https://github.com/teepluss/laravel4-theme theme package. It can be altered to whatever you need.