我在jade模板中有以下功能:
-function prettyDate(dateString){
-var date = new Date(dateString);
-var d = date.getDate();
-var monthNames = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ];
-var m = monthNames[date.getMonth()];
-var y = date.getFullYear();
-return d+' '+m;
-}
并使用以下代码调用:
td #{prettyDate(c.dateStart)}
但是我收到了错误:
undefined is not a function
但它显然是一种功能。我做错了什么?
如果你感兴趣,这里是完整的玉石模板:
extends ../layout
-function prettyDate(dateString){
-var date = new Date(dateString);
-var d = date.getDate();
-var monthNames = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ];
-var m = monthNames[date.getMonth()];
-var y = date.getFullYear();
-return d+' '+m;
-}
block content
div#highlighted
div.container
div.row-fluid.header
h2.page-title
span Courses
div#content
div.container.portfolio
div.row
div.span7.project-photos
each c in course
div.block.course-snippet
h3.block-title
span: a(href='/courses/#{c.shortTitle}') #{c.title}: #{c.type} (ages #{c.ageLow}-#{c.ageHigh})
dl
dt Dates
dd #{c.dateStart} - #{c.dateEnd}
dt Tutors
dd Names hidden
dt Fee
dd #{c.fee}
dt Course Description
dd #{c.shortDescription}
a.btn.btn-primary(href="/courses/#{c.shortTitle}") More details
|
a.btn.btn-primary(href="/booking/#{c.shortTitle}") Book a place now
div.span5.sidebar.sidebar-right
h3 Full Course Schedule
table#courses-table
thead
tr
td Start date
td End date
td Course
td Age range
td Fee (£)
tbody
each c in course
tr
td #{prettyDate(c.dateStart)}
td #{c.dateEnd}
td
a(href="/courses/#{c.shortTitle}") #{c.title}
td #{c.ageLow}-#{c.ageHigh}
td #{c.fee}
答案 0 :(得分:1)
现在已经通过将该函数移动到app.js文件中的app.locals来解决这个问题:
app.locals.prettyDate = function(dateString){
var date = new Date(dateString);
var d = date.getDate();
var monthNames = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ];
var m = monthNames[date.getMonth()];
var y = date.getFullYear();
return d+' '+m;
}
该功能可在模板中使用,如上所述。
答案 1 :(得分:0)
我发现这篇文章似乎有效。
https://www.filosophy.org/post/34/using_javascript_functions_within_the_jade_templating_language/
将你的功能变成一个变量,你应该好好去。
-var prettyDate = function (datestring){