Thursday, May 9, 2013

web2py Dynamically change highlighted class for response.menu

I'm trying to add simple function to my website but didn't know what to do. Niphlod provided me the snippet in web2py forum so I can share it here!

1. Create new app called "highlight"

2. Overwrite the response.menu in menu.py


response.menu = [
    (SPAN('Home', _id='default_highlighted'), False, URL('default', 'index'), []),
    (SPAN('Menu1'), False, URL('default', 'menu1'), []),
    (SPAN('Menu2'), False, URL('default', 'menu2'), [])
]

3. add the following script right before </head> in layout.html



<script>
jQuery(function() {
  var path = location.pathname.substring(1);
    if ( path ) {
        var els = jQuery('ul.nav a[href$="'+path+'"]').filter("[rel!=nofollow]");
        if (els.length != 0) {

            els.find('span').addClass('highlighted');
        } else {
            jQuery('#default_highlighted').find('span').addClass('highlighted');
        }
    }
})
</script>


4. Create empty action in controllers/default.py for test purpose


def index():
    return dict('')

def menu1():
    return dict('')

def menu2():
    return dict('')

5. And empty views default/menu1.html and default/menu2.html

6. TA-DA