Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use JSON.parse in nunjucks

i am get data in mongodb and express return occurs without errors but I wanted to use JSON.parse in the final results of my .find see below how I'm trying to do this

  app.get("/login", (req, res) => {
    var credentialClient = {
      expire_at: false,
      __v: false,
      _id: false
    };

    rememberMe.find({ username: "test-login" }, credentialClient, function (err, credentialInfo) {
      if (err) {
        res.send(err);
      } else {
        res.render("login.html", {
          usernameClient: JSON.parse(credentialInfo)
        });
      }
    });
  });

Without JSON.parse the final rendering stays that way in my login.html

{ username: 'test-login' }

The final results appear in login.html

<p class="center-align black-text" id="preFinalCredentialClient">{{ usernameClient }}</p>

Thanks for helping me!

like image 373
Gabriel Avatar asked Nov 20 '17 23:11

Gabriel


3 Answers

credentialInfo is already JS object, no need to parse it.

app.get("/login", (req, res) => {
    var credentialClient = {
      expire_at: false,
      __v: false,
      _id: false
    };

    rememberMe.find({ username: "test-login" },
         credentialClient, function (err, credentialInfo) {
      if (err) {
        res.send(err);
      } else {
        res.render("login.html", {
          usernameClient: credentialInfo
        });
      }
    });
  });

<p class="center-align black-text" id="preFinalCredentialClient">{{ usernameClient.username }}</p>

On the client, you can then access the properties of usernameClient.

like image 110
codejockie Avatar answered Nov 16 '22 13:11

codejockie


I hope below code will work for you. In below example, I have kept static json data. In your case you can store json data in any variable and render

index.nunjucks passing that variable.

var express = require( 'express' ) ;

var nunjucks = require( 'nunjucks' ) ;

var app = express() ;

app.get( '/', function( req, res )

 {

var jsondata = 

{

firstName: "Rakesh",
lastName: "Barani"

};

return res.render('index.njk', {data:jsondata}) ;

res.render('index.njk', {data: jsondata})
});
like image 30
AJRakesh Avatar answered Nov 16 '22 14:11

AJRakesh


It already returns JSON response so You can use this:

res.render("login.html", {
   usernameClient: credentialInfo.username
});
like image 1
ravi Avatar answered Nov 16 '22 14:11

ravi