Search code examples
javascriptnode.jsexpresspugmixins

Doing calculations with a mixin without using inline javascript


So I'm using a mixin to display a series of entries in my web app. I want each one to have a relative time stamp that says how long ago it was posted.

mixin listTitles(titles)
  each title in titles
     article.leaf
      article
    a.headline(href=title.URL)= title.title
  footer
    p.postData 
     | Posted 
     span#date=title.time
     a(href='someSource') The New York Times <br>
    a.commentButton(href=title.URL)
    a.sourceButton(href='#')
mixin listTitles(titles)

title.time contains the time of submission in javascript time (unix time in ms). I would like to compare that to the current time and display the time since the post was submitted.


Solution

  • You can use JS anywhere inside Jade template by placing - in beginning of a line.

    mixin listTitles(titles)
      - var now = Date.now();
      each title in titles
        p Posted #{now - title.time} millis ago.
    

    I assume that by “no javascript” you mean that this logic should be implemented in template itself and not js-file that calls render().