Search code examples
node.jshandlebars.js

Handlebars: disable some content based on the url


I have a basical layout with a sidebar. I want to hide the sidebar when I am on /users/profile. How can I do it using the if helper? Is there a way to get the current file name? Here is the code:


<div class="wrapper">
    {{#if user}}
      <nav id="sidebar">
        <div class="sidebar-header">
          <h3>Options</h3>
        </div>

        <ul class="list-unstyled components">

          <li class="active">
            <h1>
            <a href="/users/search"  style="color: white">Home</a>
            </h1>
          </li>
          <li>
            <h1>
            <a href="/users/chatlist"  style="color: white">Chat</a>
            </h1>
          </li>
          <li>
            <h1>
            <a href="daaggiungere" style="color: white">About us</a>
            </h1>
          </li>
        </ul>
      </nav>
        {{else}}

        {{/if}}

With the current code if a user is logged in the sidebar is showed , otherwise it is hidden. I want the same behaviour also if I am on users/profile.


Solution

  • Your routing is handled by Node.js. Somewhere in your Node.js you probably have instructions on what to do when the user opens /users/chatlist or /users/search, e.g. you select which template to render. Once you know the request is for route /users/profile, you use a JSON payload for your handlebars to properly render the page. You can customize that payload as you wish, including adding some helper fields. For example it may look like:

    {
        user: { ... },
        sidebar: {
            visible: false
        }
    }
    

    Then inside your template, you may use it for a conditional check, like:

    {{#if sidebar.visible}}
        <nav id="sidebar">
            ...
        </nav>
    {{/if}}