javascriptnode.jspassport.jsejsswig-template

Embedding user object using ejs


I'm currently implementing authentication for a web application in Node.js using the passport module. I am returning the user object to the user when rendering the index page

app.route('/').get(function(req, res) {
    res.render('index', {
        isAuthenticated: req.isAuthenticated(),
        user: req.user //User Object provided by passport
    });
});

and I'm trying to embed the user object into the DOM using ejs:

<!--Embedding The User Object-->
<script type="text/javascript">
    var user = <%= user%>;
</script>

but there are some encoding issues. This is the output when I view the source code in the browser:

<!--Embedding The User Object-->
    <script type="text/javascript">
        var user = { email: &#39;test@gmail.com&#39;,
  roles: [ &#39;user&#39; ],
  created: Thu Feb 04 2016 19:13:16 GMT+1100 (AEDT),
  __v: 0,
  _id: 56b3081cb406f8156cd3798a };
</script>

I am following an example that uses swig in which they handle the encoding like so:

<!--Embedding The User Object-->
<script type="text/javascript">
    var user = {{ user | json | safe }};
</script> 

I'm not too familiar with swig so I assume it is some sort of pipelining. I was wondering how I would do this using ejs?


Solution

  • RESOLVED! EJS has a html escaping function which is as simple as

    <%- user %>
    

    instead of

    <%= user %>