Search code examples
knockout.jsdurandalhottowel

Add image to navigation


Im using the hot towel template and I would like to add a different image for each navigation route. How would i accomplish this? At the moment its just using the same image.

Here is my code for routing

     function boot() {
        router.mapNav('home');
        router.mapNav('details');
        router.mapNav('myPage');

        log('Hot Towel SPA Loaded!', null, true);
        return router.activate('home');
    }

Knockout code

   <div id="frame">
        <ul class="project-list" data-bind="foreach: router.visibleRoutes">
            <li data-bind="css: { current: isActive }"><a data-bind="attr: { href: hash }" class=""
                href="#"><span class="image"><i class="icon-desktop"></i></span><span class="title"
                    data-bind="text:name"></span></a></li>
        </ul>
    </div>

Solution

  • You can use the mapNav other overload which takes an object as the first argument where you can add custom properties like:

    router.mapNav({url: 'myPage', image: 'icon-desktop'});
    router.mapNav({url: 'myPage', image: 'icon-something'});
    router.mapNav({url: 'myPage', image: 'icon-somethingelse'});
    

    And in your view you can just write:

    <span class="image">
       <i data-bind="css: image"></i>
    </span>
    

    Or if you want to specify real image urls you can also do that:

    router.mapNav({url: 'myPage', imageUrl: 'http://server.com/myimage.png'});
    
    <span class="image">
       <img data-bind="attr: { scr: imageUrl }"></i>
    </span>
    

    Alternativly to avoid conflicts with durandal's own properties you can put your custom settings on a settings object

    router.mapNav({url: 'myPage', { settings: { image: 'icon-desktop'}});
    

    And in your view:

    <span class="image">
       <i data-bind="css: settings.image"></i>
    </span>