Finding current url inside EJS view when using express

后端 未结 3 1556
鱼传尺愫
鱼传尺愫 2020-12-11 17:51

I\'m using Express and EJS to serve pages. I\'m using Bootstrap for the UI, specifically the navbar.

I\'d like to add an \'active\' class to the current

3条回答
  •  感情败类
    2020-12-11 18:48

    index.js

    /* object menu */
    const menu = [
        {
            name: 'Home',
            url: '/'
        },
        {
            name: 'About',
            url: '/about'
        }
    ]
    
    /* route */
    app.get( '/', function( request, response) {
    
        let data = {
            title: 'Home',
            url: request.url,
            menu: menu
        }
    
        response.render( 'home', data )
    
    } )
    
    app.get( '/about', function( request, response) {
    
        let data = {
            title: 'About',
            url: request.url,
            menu: menu
        }
    
        response.render( 'about', data )
    
    } )
    

    menu.js

        <% for ( let i in menu ) { %> // loop menu
            <% if ( menu[i].url == url ) { %> // match, add active in class
    
                <%= menu[i].name %>
    
            <% } else { %>
    
                <%= menu[i].name %>
    
            <% } %>
        <% } %>
    

提交回复
热议问题