2013-01-16 39 views
0

所以我使用mixin在我的web應用程序中顯示一系列條目。我希望每個人都有一個相對的時間戳,說明它發佈多久之前。使用mixin進行計算而不使用內聯javascript

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包含在javascript時間內提交的時間(以毫秒爲單位的unix時間)。我想將其與當前時間進行比較,並顯示帖子提交後的時間。

回答

0

通過將-放置在行的開頭,您可以在Jade模板內的任意位置使用JS。

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

我認爲是「非JavaScript」你的意思是,這個邏輯應該在模板本身,而不是JS文件調用render()實現。

+0

由no javascript我的意思是我希望邏輯在script.js中,而不是在模板中。你知道是否有性能上的缺點嗎?因爲我打算將時間轉換爲分鐘,幾小時和幾天,並將其連接起來。 – user1816679

+0

@ user1816679當然你可以:計算它並傳遞給'render'函數,就像你傳遞'titles'一樣。 (請參見['app.locals'](http://expressjs.com/api.html#app.locals)和['res.locals'](http://expressjs.com/api.html#res.locals )在Express中。)Jade編譯爲JS函數,所以我不認爲會有重大改進。你還需要嗎?恕我直言,這是關於代碼的結構。對於Jade選項,使用'self:false'和'compileDebug:false'的緩存模板是更好的性能投資(請參閱Google上的這些)。 – elmigranto

+0

moment.js有一些方便的時間以前的方法http://momentjs.com/例如。 'moment(「20130218」,「YYYYMMDD」)。fromNow();' –