Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set navigation menu item active in Handlebars partial

Currently, I am repeating code for my navigation menu on every single tab, but I want to use partials so there's no duplicate code.

This is what I am using (below), with the active class on a different list element depending on the file. Instead, I'd like to use a partial {{> fruits-nav}}, but I can't find any information on how I would set the active class depending on which file is including the partial.

<div id="table-nav-tabs">
    <ul class="nav nav-tabs">
        <li class="apple"><a href="{{id}}">apple</a></li>
        <li class="active orange"><a href="{{id}}">orange</a></li>
        <li class="mango"><a href="{{id}}">mango</a></li>
        <li class="pineapple"><a href="{{id}}">pineapple</a></li>
    </ul>
</div>
like image 896
theintellects Avatar asked Jun 11 '13 17:06

theintellects


2 Answers

You can pass data to a partial so you can do this in your partial:

<div id="table-nav-tabs">
    <ul class="nav nav-tabs">
        <li class="{{#if active_apple}}active{{/if}} apple"><a href="{{id}}">apple</a></li>
        <li class="{{#if active_orange}}active{{/if}} orange"><a href="{{id}}">orange</a></li>
        <li class="{{#if active_mango}}active{{/if}} mango"><a href="{{id}}">mango</a></li>
        <li class="{{#if active_pineapple}}active{{/if}} pineapple"><a href="{{id}}">pineapple</a></li>
    </ul>
</div>

and then pull it in like this:

{{> fruits-nav active}}

and just make sure active has he appropriate flag set for the current fruit.

Demo: http://jsfiddle.net/ambiguous/GesND/

like image 158
mu is too short Avatar answered Nov 04 '22 20:11

mu is too short


I think you can even make it slightly simpler and more readable:

<div id="table-nav-tabs">
    <ul class="nav nav-tabs">
        <li class="{{#if active.apple}}active{{/if}} apple"><a href="{{id}}">apple</a></li>
        <li class="{{#if active.orange}}active{{/if}} orange"><a href="{{id}}">orange</a></li>
        <li class="{{#if active.mango}}active{{/if}} mango"><a href="{{id}}">mango</a></li>
        <li class="{{#if active.pineapple}}active{{/if}} pineapple"><a href="{{id}}">pineapple</a></li>
    </ul>
</div>

and while rendering:

active: { pineapple: true }
like image 39
Flaudre Avatar answered Nov 04 '22 19:11

Flaudre