htmlnode.jsexpresshandlebars.jsexpress-handlebars

Interpolate variable inside "each" loop in Handlebars


I am rendering this in an express app which uses handlebars as template engine:

 res.render("movies", { data: pages, arraypages:arrayPages, movie:movie})

"arrayPages" is an array: [ 1, 2, 3, 4, 5, 6, 7 ]

"movie" is a string like "top gun"

Inside the handlebars template there is:

{{#each arraypages}}
<form action="/getmoviepage" method="post">
    <a>{{this}}</a>
    <input type="hidden" name="{{movie}}" value="{{this}}">
</form>
{{/each}}

Which outputs:

<form action="/getmoviepage" method="post">
    <a>1</a>
    <input type="hidden" name="" value="1">
</form>

<form action="/getmoviepage" method="post">
    <a>2</a>
    <input type="hidden" name="" value="2">
</form>

<form action="/getmoviepage" method="post">
    <a>3</a>
    <input type="hidden" name="" value="3">
</form>

<form action="/getmoviepage" method="post">
    <a>4</a>
    <input type="hidden" name="" value="4">
</form>

<form action="/getmoviepage" method="post">
    <a>5</a>
    <input type="hidden" name="" value="5">
</form>

<form action="/getmoviepage" method="post">
    <a>6</a>
    <input type="hidden" name="" value="6">
</form>

<form action="/getmoviepage" method="post">
    <a>7</a>
    <input type="hidden" name="" value="7">
</form>
    


As you can see the "movie" variable is not rendered (the variable should render inside the "name" attribute). If I put the variable outside the "each" loop is rendered OK.

{{movie}}  //This is rendered OK, outside the "each" loop
{{#each arraypages}}
<form action="/getmoviepage" method="post">
    <a>{{this}}</a>
    <input type="hidden" name="{{movie}}" value="{{this}}">
</form>
{{/each}}

How do I render a variable inside a "each" loop in handlebars?


Solution

  • Try

    <input type="hidden" name="{{../movie}}" value="{{this}}">
    

    The ../ path segment references the parent template scope that should be what you want.

    Potential Duplicate Question