Skip to content

Instantly share code, notes, and snippets.

@J5Dev
Last active August 29, 2015 14:02
Show Gist options
  • Save J5Dev/0a5757a2a7d47d4a7ac1 to your computer and use it in GitHub Desktop.
Save J5Dev/0a5757a2a7d47d4a7ac1 to your computer and use it in GitHub Desktop.
Laravel 4 HTML macro to generate link within a list from a string or route, including active status if current url
<?php
HTML::macro('navLink', function ($route, $text, $listAttributes = [], $linkAttributes = [], $params = null, $secure = null)
{
# Set default attributes
$listDefaults = ['class' => ''];
$linkDefaults = ['class' => ''];
// Merge default attributes with those supplied
$listAttributes = $listDefaults + ($listAttributes == null ? [] : $listAttributes);
$linkAttributes = $linkDefaults + ($linkAttributes == null ? [] : $linkAttributes);
// check if supplied route is a named route or text url
if (Route::getRoutes()->hasNamedRoute($route))
{
// create the href value
$href = route($route, $params);
// set whether the supplied route is the current url
$is_active = ($route == Route::currentRouteName());
} else
{
// check if an external domain is supplied
if( ! preg_match('/([a-z0-9\-]+)\.([a-z]+|[a-z]{2}\.[a-z]+)$/im', $route))
{
// create the href value
$href = url($route);
} else
{
$href = $route;
}
// check whether the supplied url is the current on or a child of
$is_active = Request::is($route . '*');
}
# Append active class if wanted
if ($is_active)
{
$listAttributes['class'] .= ' active';
$linkAttributes['class'] .= ' active';
}
return '<li ' . HTML::attributes($listAttributes) . '>' . link_to($href, $text, $linkAttributes, $secure) . '</li>';
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment