Skip to content

Instantly share code, notes, and snippets.

@brandonferens
Created August 20, 2014 20:23
Show Gist options
  • Save brandonferens/877bde0948f4e52550e9 to your computer and use it in GitHub Desktop.
Save brandonferens/877bde0948f4e52550e9 to your computer and use it in GitHub Desktop.
Load relative javascript assets based on route in Laravel
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();
@brandonferens
Copy link
Author

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 for public/js/admin/users/create.js, public/js/admin/users.js, and public/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.

@nateritter
Copy link

Brilliant.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment