Home > other >  Writing EJS in JS script dynamically
Writing EJS in JS script dynamically

Time:06-17

i am trying to use Leaflet API and store my users saved points(markers,circles,polygons) into a MongoDB database.

Is there a more elegant and dynamic way of writing a JS script in a HTML page while getting the results from the database?

at the moment i am getting my data from Mongo and passing it through the Get request and using that on the HTML page, writing EJS inside the JS script. it works fine but im looking into a better solution.

many thanks for your time

    // index.js
    router.get('/index', ensureAuthenticated, (req, res) => {
      var queryz = Points.find({ belongs_to: req.user._id })
      queryz.exec(function (err, results) {
        if (err) return handleError(err);

        res.render('index', {
          user: req.user,
          points: results,
        })
      })
    })
    // index.ejs
      // looping through the points from the database to dynamically add the points 
            // each time the map is called
            <% if(typeof points != "undefined") { %>  // making sure user is logged in
            <% counter = 1 %>
            <% if(points.length>0){ %>
                <% points.forEach(p => {%>
                <% if(p.type == "marker"){ %>  // if point is a marker
                    marker<%=counter%> = L.marker([<%=p.coords%>], { icon: <%=p.icon%>, alt: '<%=p.popup_message%>' }).bindPopup('<%=p.popup_message%><form method="post" action="/delete_point" id="pointFORM"><input id="pointID" name="pointID" value="<%=p._id%>"><button id="submitBtn" type="submit">           
  • Related