Laravel How to: Use custom Blade directive to make navigation item active

Jatin Prajapati
2 min readAug 9, 2019

--

Introduction

Blade is the simple templating engine provided with Laravel which is powerful as well. All Blade views are compiled into plain PHP code and cached until they are modified. Blade view files use the .blade.php file extension and they are stored into resources/views directory.

Extending Blade

You can define your own custom directives using the directive method. While compiling the Blade templates, if any custom directive is encountered, the compiler will call the provided callback with the expression that the directive contains.

You must define your custom directive in AppServiceProvider to make sure the directive is available everywhere in your application.

Example: Apply active class to navigation item for current page

Think that you are developing an application in Laravel where you have a big navigation on left hand side. Whenever you navigate to a page using, you need to apply the active CSS class to the item matching the current URL. There can be different ways to make this work but here we will see how we can use custom directive to return the active CSS class name if current route name is matching with the provided on.

In the above code snippet, I’ve defined two custom directives isactive and isactiveandopen which we can use in the blade template as following:

Make sure after changing logic of a Blade direction, you execute the php artisan view:clear command to clear cached Blade views.

Thanks and hope this will help you in your project.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response