can’t render in ejs template of node.js

can’t render in ejs template of node.js

Problem

I met a wield problem in node.js ejs template. Here is the express code.

app.get('/course',function(req,res){
     var locals = {};
     locals.course = {
            title: 'data.title',
            city: 'data.city',
            desc: 'data.desc',
            id: 'data._id'
     };         
     res.render('course_description',locals );
});

Here is the template code

<div >
  <article>
    <% if(locals.course) { %>           
            <div><% locals.course.title %></div>
            <div><% locals.course.city %></div>
            <div><% course.city %></div>
            <div><% course.title %></div>   
    <% } %>
  </article>    
</div>

when res.render(‘course_description’,locals ); is triggered, the local data should passed to the template, but for some unknown reason, it doesn’t work for this example.

all I got is 4 empty

<div >
  <article>         
            <div></div>
            <div></div>
            <div></div>
            <div></div> 
  </article>    
</div>

does anybody meet this wield problem before, I am so confused, I have done some working example before, but when I compare this with other working ones, I still can’t find the reason.

Note, I am using the latest ejs and express

Problem courtesy of: user824624

Solution

<% ... %> are for code constructions, not for output.

Try this:

<div>
  <article>
    <% if (locals.course) { %>
      <div><%= locals.course.title %></div>
      <div><%= locals.course.city %></div>
      <div><%= course.city %></div>
      <div><%= course.title %></div>
    <% } %>
  </article>
</div>
Solution courtesy of: robertklep

Discussion

Leave a Reply

Your email address will not be published. Required fields are marked *