0

I want to display another view if there is :id in Semantic URL

app.get(['/topic', '/topic/:id'], function(req, res){
  id = req.params.id    
  if(id){
    res.render('view',{topics:rows, topic:row[0]}
  }else{
    res.render('view', {topics:rows}
  }
}

and view.ejs

for(var i = 0; i < topics.length; i++){
 <li><%= topics[0].title%></li>
}
<% if(topic) {%>
  <%= topic.description %>
<%} else {%>
  <h1>Welcome</h1>
<% } %>

it did works correctly when i connect to localhost:3000/topic/1

but when i connect to localhost:3000/topic

console said topic is not defined

what is the problem?

When i use

res.render('views', {topics:rows, topic:''}

it did works correctly

Do i have to use like this?

PrepareFor
  • 2,448
  • 6
  • 22
  • 36

1 Answers1

1

In view.ejs it is best to check the if condition as follows. Not only in ejs but in entire javascript world

<% if(typeof topic !== 'undefined') {%>
   <%= topic.description %>
<%} else {%>
   <h1>Welcome</h1>
<% } %>

And you can use also use res.render('views', {topics:rows, topic:''}

Bharathvaj Ganesan
  • 3,054
  • 1
  • 18
  • 32