user17816100
user17816100

Reputation:

Pass data in header with express-handlebars

I have a NodeJS app that I want to pass email into the header in my "main.hbs" when I register or log in. Maybe redirect should be different.

This is my register action:

router.post('/register', async (req, res) => {
const { firstName, lastName, email, password, rePassword } = req.body;

const user = await authService.register({ firstName, lastName, email, password });
const token = authService.createToken(user);

res.cookie(sessionName, token);

res.redirect('/');
});

And this is my template:

<div id="box">
    {{#if error}}
    <div class="error-container">
        <p>{{error}}</p>
    </div>
    {{/if}}

    <nav>
        <!-- Do not forget to change the path to the image -->
        <img src="/img/logo.png" alt="logo">

        <ul class="menu">
            <li><a href="/">Home</a></li>
            <li><a href="/posts/all">All Posts</a></li>
            <!-- Logged users -->
            {{#if user}}
            <li><a href="/posts/create">Create Post</a></li>
            <li><a href="/posts/user">Posts of {{email-of-user}}</a></li> // Here I want to pass my email
            <li><a href="/auth/logout">Logout</a></li>
            <!-- Guest users -->
            {{else}}
            <li><a href="/auth/register">Register</a></li>
            <li><a href="/auth/login">Login</a></li>
            {{/if}}
        </ul>

    </nav>


    <main>
        {{{body}}}
    </main>
</div>

Upvotes: 0

Views: 568

Answers (1)

Naveen Ravi
Naveen Ravi

Reputation: 113

In express you can pass an object to a page with render method For example imagine if the details of user is in an object called currentUser in ther server then you can send the currentUser to page by

res.render('index', {currentUser});

later you can access the object in hbs file by simply by

  <p> {{currentUser.property}} </p>

Upvotes: 1

Related Questions