Unexpected token return in ,while compiling ejs
Asked Answered
B

6

15

I am trying to develop a guestbook app which stores users names, country and users message sin mongodb, the connection is ok, I can submit these 3 infos(username, country and message)in the db. My Issue is to RENDER the messages into my "guestbook.ejs" page.

I would appreciate If anyone can give me a clue on the issue I encounter.

SyntaxError: Unexpected token return in /Users/mesfint/Desktop/MEAN_DEV'T/Guestbook-application/views/pages/guestbook.ejs while compiling ejs

If the above error is not helpful, you may want to try EJS-Lint:
https://github.com/RyanZim/EJS-Lint
   at Object.Function (<anonymous>)
   at Object.Template.compile (/Users/mesfint/Desktop/MEAN_DEV'T/Guestbook-application/node_modules/ejs/lib/ejs.js:524:12)
   at Object.compile (/Users/mesfint/Desktop/MEAN_DEV'T/Guestbook-application/node_modules/ejs/lib/ejs.js:338:16)
   at handleCache (/Users/mesfint/Desktop/MEAN_DEV'T/Guestbook-application/node_modules/ejs/lib/ejs.js:181:18)
   at tryHandleCache (/Users/mesfint/Desktop/MEAN_DEV'T/Guestbook-application/node_modules/ejs/lib/ejs.js:203:14)
   at View.exports.renderFile [as engine] (/Users/mesfint/Desktop/MEAN_DEV'T/Guestbook-application/node_modules/ejs/lib/ejs.js:412:10)
   at View.render (/Users/mesfint/Desktop/MEAN_DEV'T/Guestbook-application/node_modules/express/lib/view.js:126:8)
   at tryRender (/Users/mesfint/Desktop/MEAN_DEV'T/Guestbook-application/node_modules/express/lib/application.js:639:10)
   at EventEmitter.render (/Users/mesfint/Desktop/MEAN_DEV'T/Guestbook-application/node_modules/express/lib/application.js:591:3)
   at ServerResponse.render (/Users/mesfint/Desktop/MEAN_DEV'T/Guestbook-application/node_modules/express/lib/response.js:960:7)

guestbook.ejs

<!DOCTYPE html>
<html lang="en">
<head>

    <% include ../partials/head %>
</head>

<body class="container">

    <header>
        <% include ../partials/header %>


    </header>
    <main>
        <div class="jumbotron">
            <h4><%= guest_message %></h4>
           <table  border = "1">
               <tr>

                    <th>Name</th>
                    <th>Country</th>
                    <th>Message</th>
                </tr>
           <!-- <% jsonData.forEach(function(users){%>-->
            <% for(var i=0; i<newmessage.length; i++) {%>


                <tr>

                    <td class="userInput"><%= newmessage[i].username %></td>
                    <td class="userInput"><%= newmessage[i].country %></td>
                    <td class="userInput"><%= newmessage[i].message %></td>
                </tr>


            <%} %>
            </table>

</div>
    </main>

     <footer>
<% include ../partials/footer %>
</footer>
</body>

</html>

server.js

    var express = require("express");
    var bodyParser = require('body-parser');
    var app = express();
    var fs = require("fs");
    var MongoClient = require('mongodb').MongoClient;

    var db;


app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(express.static('public'));

    MongoClient.connect('mongodb://mesfin:######@ds137090.mlab.com:37090/guestbook', function(err, database)  {
  if (err) return console.log(err)
  db = database;
  app.listen(3000, function () {
    console.log('listening on 3000');
  })
})

    app.get("/", function(req,res){
    res.render("pages/index", {

        title_index: "What we speak?",
         content_index:"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore",

         footer_index:"My footer goes here"
        });


    });


    app.get("/guestbook", function(req,res){

       // res.render("pages/guestbook",{
      db.collection('newmessage').find().toArray(function (err, result)  {
    if (err) return console.log(err)
    res.render('pages/guestbook', {newmessage: result});

  });

        });


    app.get("/newmessage", function(req,res){
        res.sendFile(__dirname  + "/pages/newmessage");

        res.render("pages/newmessage",{
            add_newMessage:"Add Your info & message!"
        });

    });

    app.post("/newmessage" , function(req,res){
db.collection('newmessage').save(req.body, function(err, result) {
    if (err) return console.log(err);
    console.log('saved to database');
    res.redirect('/');
  });

    });

sample insertd data from Mongodb

Brassbound answered 23/3, 2017 at 11:21 Comment(4)
Should be <%- include, not <% include.Delouse
Thanks @BenFortune, But still i see NO difference on the output, but appreciate!Brassbound
Try change <% include ../path/to/include %> with <%- include ('../path/to/include') %>Arbitral
@ponury-kostek, No change , but thanksBrassbound
A
26

Instead of

 <% include ../partials/head %>

Write

<%- include ("../partials/head") %>
Archivist answered 25/2, 2020 at 20:54 Comment(3)
Template tag <%- outputs the unescaped value into the template, whereas <% 'scriptlet' tag is used for control-flow, no output. The paranthesis and " " are used for filename location.Archivist
so this syntax has changed with a newer version, right?Offutt
As far as I know they were since creation of ejs, but each tag has its own utility. You can see all the tags here.Archivist
A
5

Add <%})%> before </table> or remove <!-- <% jsonData.forEach(function(users){%>--> because you don't close forEach

HTML comment <!-- --> don't affects ejs. You can use {# #} instead.

Arbitral answered 23/3, 2017 at 14:47 Comment(0)
S
5

In my case, I found that error on include partial templates like below

<% include ./partials/messages %>

so I change it with following

<%- include ('partials/messages') %>

that's works for me, hope it helps

Stupe answered 12/2, 2020 at 11:41 Comment(0)
K
4

remove unnessary <% %> tags in your code

Kufic answered 11/9, 2018 at 9:44 Comment(1)
Unexpected token due to your embedded ejs attributes not match in output data elements .for eg. your server side data like var data = {"name":"Joseph","age":21}; your ejs page code might be <%=data.name %> <%= data.age%> apart from this data <%= %> this unwanted tag through error msg .Kufic
I
-1

The problem is in your node routes. In your /newMessage route rewrite

res.render("pages/newmessage", 

to

res.render("/pages/newmessage",

Also in your /guestbook route rewrite

res.render("pages/guestbook", 

to

res.render("/pages/guestbook",

Try checking this article on node routes https://dev.to/ericchapman/nodejs-express-part-5-routes-and-controllers-55d3

Icily answered 17/11, 2021 at 5:0 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Borstal
B
-1

In my case, I found that error on include partial templates like below <% include .partials/messages %> so I change it with following <%- include (".partials/messages") %>

Bingle answered 1/1, 2023 at 3:43 Comment(1)
Hi, rember to format your code using the visual editor or markdown syntax. Docs hereGangplank

© 2022 - 2024 — McMap. All rights reserved.