Posted by Arjun on Sunday 23rd November 2014

Laravel Bootstrap Alert macro

Laravel allowing us to extend the HTML facade with additional functionality. we use the HTML::macro() method to extend the HTML facade with our own methods.So here is the Twitter Bootstrap alert macro.

Place the below macro code into your app/start/global.php file to register it.

HTML::macro('alert', function($type, $message, $head = null,$noHead = false) {
switch ($type) {
	case 'success': //green color
		$head = $head ? $head : 'Success';
		break;
	case 'danger': //red color
		$head = $head ? $head : 'Error';
		break;
	case 'warning': //yellow color
		$head = $head ? $head : 'Warning';
		break;
	case 'info': //blue color
		$head = $head ? $head : 'Info';
		break;
}
return $noHead ? '<div class="alert alert-'. $type .'">' . $message . '</div>':'<div class="alert alert-'. $type .'"><strong>'. $head .': </strong>' . $message . '</div>';
});
 

How to use

Then place place this code in your blade template.

With Default head

{{ HTML::alert('success', 'your message') }} 
// output:  <div class="alert alert-success" role="alert"><strong>success</strong> your message </div>
{{ HTML::alert('danger', 'your message') }} 
// output : <div class="alert alert-danger" role="alert"><strong>danger</strong> your message</div>
{{ HTML::alert('warning', 'your message') }} 
// output : <div class="alert alert-warning" role="alert"><strong>warning</strong> your message</div>
{{ HTML::alert('info', 'your message') }} 
//output : <div class="alert alert-info" role="alert"><strong>info</strong> your message</div>

With custom head

{{ HTML::alert('success', 'your message','Success message') }} 
// output:  <div class="alert alert-success" role="alert"><strong>Success message</strong> your message </div>
{{ HTML::alert('danger', 'your message','Danger message') }} 
// output : <div class="alert alert-danger" role="alert"><strong>Danger message</strong> your message</div>
{{ HTML::alert('warning', 'your message','Warning message') }} 
// output : <div class="alert alert-warning" role="alert"><strong>Warning message</strong> your message</div>
{{ HTML::alert('info', 'your message','Info message') }} 
//output : <div class="alert alert-info" role="alert"><strong>Info message</strong> your message</div>

Without head

{{ HTML::alert('success', 'your message',null,true) }} 
// output:  <div class="alert alert-success" role="alert"> your message </div>
{{ HTML::alert('danger', 'your message',null,true) }} 
// output : <div class="alert alert-danger" role="alert">your message</div>
{{ HTML::alert('warning', 'your message',null,true) }} 
// output : <div class="alert alert-warning" role="alert">your message</div>
{{ HTML::alert('info', 'your message',null,true) }} 
//output : <div class="alert alert-info" role="alert">your message</div>