Cesare
Cesare

Reputation: 9419

Access to variables inside EJS

I want to use the objects I pass from map.js to map.ejs. In my request, I fetch the objects:

module.exports = async function(req, res) {
    var myObjects = await new Promise(resolve => {
        // resolve with objects
    });

    res.view('pages/map/home', {
        myObjects
    })
};

How can I access my objects in my .ejs file? I would like to loop through them to add them on the map, however, this doesn't print anything. It actually creates errors on the page. Part of map.ejs

<div id="mapid"></div>
<script>
// set up map
var mymap = L.map('mapid').setView([45.4735629, 9.1771209], 13);
// ...
// add markers on map using fetched objects
var myObjects = <%- myObjects %>
myObjects.forEach(f => {
    var marker = L.marker([f.latitude, f.longitude]).addTo(mymap); 
}
</script>

I get Unexpected identifier on myObjects in .ejs. Any hints on what I'm doing wrong?

Upvotes: 0

Views: 87

Answers (1)

Bibberty
Bibberty

Reputation: 4768

Leave you map route to render the view map.ejs
This will send the HTML to the client.

So you view route might look like this:

router.get('/', (req, res) => {
    res.send('home', {})
});

Add a route for return map points e.g. [site]/maps/getMapPoints/:location

From that route simply respond with JSON.

Here is an example of an API Route

/* GET home page. */
router.get('/', (req, res) => {
  geoLocate(req.ip).then(json => {
    res.json(json);
  }).catch(err => console.log(err));
});

Now in the client HTML that was rendered by you map.ejs you will need to consume this. We will use this REST Test Site

// When the DOM has loaded.
document.addEventListener('DOMContentLoaded', () => {
  fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(res => res.json())
  .then(json => {
    // Lets build out the HTML
    document.querySelector('.container').innerHTML = `
      <div id="${json.id}"><h3>${json.title} - ${(json.completed) ? 'Complete' : 'Pending'}</h3></div>
    `;
  });
});
<div class="container">

</div>

Finally here is a working example of the seperation: Sample Site

Upvotes: 1

Related Questions