Created
April 2, 2017 16:45
-
-
Save 0xShamil/c25fd1827e81d3e9413fe631df0b50d9 to your computer and use it in GitHub Desktop.
Add active class to bootstrap link components in Laravel 5
This file contains 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
<?php | |
/** | |
* Load this file with composer autoload | |
*/ | |
if (! function_exists('active')) { | |
function active($route, $class = 'active') | |
{ | |
/** | |
* Route checking can be done here, | |
* but doing it in a seperate class file is a bit cleaner and maintainable | |
*/ | |
return RouteActiveStateChecker::active($route, $class); | |
} | |
} | |
This file contains 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
<?php | |
use Route; | |
/** | |
* Create this file in app/ directory. | |
* Set namespace. | |
* Import it in helpers.php to use the static methods | |
*/ | |
class RouteActiveStateChecker | |
{ | |
/** | |
* Determine if the provided route is active. | |
* | |
* @param string $route | |
* @return bool | |
*/ | |
static function isActiveRoute($route) | |
{ | |
if (Route::currentRouteName() == $route) { | |
return true; | |
} | |
return false; | |
} | |
/** | |
* Get the active class if the active path is provided. | |
* | |
* @param string $route | |
* @param string $class | |
* @return string|null | |
*/ | |
static function active($route, $class='active') | |
{ | |
return self::isActiveRoute($route) ? $class : null; | |
} | |
} |
This file contains 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
<ul class="nav"> | |
<li class="{{ active('dashboard.index') }}"> | |
... | |
</li> | |
<li class="{{ active('posts.index') }}"> | |
.... | |
</li> | |
<li class="{{ active('categories.index') }}"> | |
... | |
</li> | |
</ul> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment