0

I have a product search result prodArray that is used in rendering my .ejs script. It is made up of a number of objects based on the previous query. Each object will contain a startDate field which is a Date() object. I want moment.js to display this date in a more pleasing way (a format that I decide). I populate the <span> tag with my date.toString() using ejs. I then want jQuery to pick this up when the document is loaded and present it in my desired format.

This might not be the best way to do things. I am open to any suggestions.

My .ejs code is as follows:

<h1>My List of products</h1>
<% prodArray.forEach(function (product) { %>
  <div class="product">
    <h2><%= product.name %></h2>
    <p>Starting: <span class="moment"><%= product.startDate.toString() %></span><br/>
    Places: <%= product.places.max %><br/>
    </p>
  </div>
<% }) %>

<script>
  $(document).ready(function () {
    // $('.moment').text( moment( $(this).text() ).format('MMM Do YYYY hh:mm') )
    // DOES NOT RUN.

    // $('.moment').text( moment( $(this).contents() ).format('MMM Do YYYY hh:mm') )
    // POPULATES ALL MY PRODUCTS WITH THE SAME DATE

    // $('.moment').text( moment( $(this).val() ).format('MMM Do YYYY hh:mm') )
    // POPULATES ALL MY PRODUCTS WITH 'INVALID DATE'

    /* 
    $('.moment').on("ready",function () {
      var datestr = $(this).text();
      $(this).text(moment(datestr).format('MMM Do YYYY hh:mm'))
    })
    DOES NOT AFFECT ANYTHING. */
  })
</script>

Some of the things that I have tried are commented out in the script and their effects are written bellow each of them. Is there a

$(.moment).nothinghappened(function () {
// blah
})

event?

If you have any suggestions I would really appreciate it.

2 Answers2

0

I think you can do something like

<p>Starting: <span class="moment"><%= moment(product.startDate).format('dd-MMM-YYYY') %></span><br/>
Zohaib Ijaz
  • 21,926
  • 7
  • 38
  • 60
  • only seeing your answer now. You also need to pass moment as a local variable as I have showed in my answer. Thanks for taking the time to help me out. – seamusgalla Nov 19 '15 at 20:42
0

So I solved this by eliminating the need to use moment on the client side. If you pass moment as a local variable when rendering you ejs.

var moment = require('moment')
router.get('/product', function (req,res,next) {
  mongoose.model('products').find({}).exec(functions (error, prodArray) {
    res.render('productTemplate',{
      prodArray: prodArray,
      moment: moment
    })
  })
})

You can then use it like so

<p>Starting: <span class="moment"><%= moment(product.startDate).format('MMM Do YYYY hh:mm') %></span>

in your template.

Credit due to @Sean Murin and @Zohaib Ijaz