How to pass an array in hogan-express template engine

574 views Asked by At

How do I pass an array like the below to a HTML page using hogan-express? I am trying but it doesn't seem to be working.

My code:

apiRouter.get('/myPosts', function(req, res, next){
    userModel.findOne({'profileID':req.session.facebookProfileId}, function(err, userPosts) {
            if(userPosts) {
                res.render('myPosts', {title:siteName + ': My Posts', posts:userPosts.posts});
            } else {
                console.log('You do not have any posts');
            }
        })
})

By the way, the userPosts.posts looks like the below:

["123","124","125"]

myPosts.html page is as below:

<!doctype html>
<head>
<meta charset="UTF-8">
<title>{{title}}</title>
</head>
<body>
    <p><a href="/posts?id={{posts[0].value}}">Post 1</a></p>
    <p><a href="/posts?id={{posts[1].value}}">Post 2</a></p>
</body>
</html>

By the way, the {{title}} bit is coming through.

1

There are 1 answers

1
robertklep On BEST ANSWER

In short: you can't, at least not like that.

What you can do is iterate over the posts:

{{#posts}}
  <p><a href="/posts?id={{.}}">Post 1</a></p>
{{/posts}}

However, that would leave you with the problem of the text content for each link ("Post 1"). To fix that, you need to process the array server-side, before you pass it to render.

For example:

res.render('myPosts', {
  title : siteName + ': My Posts',
  posts : userPosts.posts.map(function(postId, idx) {
    return { postId : postId, postNum : 1 + idx };
  })
});

And the template:

{{#posts}}
  <p><a href="/posts?id={{postId}}">Post {{postNum}}</a></p>
{{/posts}}

The rendered HTML will look like this:

<p><a href="/posts?id=123">Post 1</a></p>
<p><a href="/posts?id=124">Post 2</a></p>
<p><a href="/posts?id=125">Post 3</a></p>