简体   繁体   中英

In Nodejs, how can i check params in Ejs render

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?

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:''}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM