Thursday, 25 May 2017

How to access server-side variable in EJS view?

I'm new to Javascript and I'm trying to access a json-object passed from my server. For some reason I get syntax-error when trying to convert it to a javascript object in the ejs view. If embedded directly in the html, like the title, it works. But I would like to work with the passed "events" data in javascript first, then append it to the "eventsTarget" div.

The syntax error is "Type expected" at the first %-sign. The closing % sign gives "Expresstion expected".

How can I make this work?

This is my server-file

/****** REQUIREMENTS *******/
var express = require('express');
var router = express.Router();
var request = require('request');
var ejs = require('ejs');


/****** ROUTING *******/
// GET decore page. 
router.get('/', function (req, res, next) {

    console.log('Message from GET/ decore');
    SOAProjectApi(function (events) {

        res.render('decore',
            {
                title: 'Decore',
                events: events
            });
    })
});

/* FETCHING SOA-PROJECT API (Events) */

function SOAProjectApi(cb) {

    request({
        url: 'http://x.azurewebsites.net/api/publish/events'
        ,
        method: 'GET'
    }, function (err, res) {
        var events = JSON.parse(res.body); 

        cb(events);
    });
}

module.exports = router;

Here is the .ejs view

<h2><%= title %></h2>

<% if (events) { %>

<script>
 var e = <%- events %>
 /* 
   I have also tried these options

   var e = <%= events %>
   var e = <% events %>
 */
</script>

<% } %>



via jeth0010

No comments:

Post a Comment