![](/img/trans.png)
[英]How can I fetch a json file using Vapor for my leaf template to show the data?
[英]How to format a date field in a Leaf template using Vapor 4
在列表中,我想顯示從數據庫中獲取的日期。 如果我使用:
#Date(timeStamp: appointment.appointmentDate,localizedFormat: "E, dd-MM-yyyy")
我希望:星期三, 2020年 12 月 30 日,但我得到了星期三, 2020年 12 月 30 日,我覺得這很奇怪,因為我特別要求dd-MM
然后我嘗試了:
#Date(timeStamp: appointment.appointmentDate,fixedFormat: "E, dd-MM-yyyy")
工作正常並為我提供:星期三,2020 年 12 月 30 日
不過,我還是不開心……
和
創建葉子方法:
import Foundation
import Leaf
public struct DataLeafFunction: LeafFunction, StringReturn, Invariant {
public static var callSignature: [LeafCallParameter] { [
.double,
.string(labeled: nil, optional: true, defaultValue: "yyyy-MM-dd")
] }
public func evaluate(_ params: LeafCallValues) -> LeafData {
guard let timestamp = params[0].double else { return .string(params[0].string) }
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = params[1].string
let date = Date(timeIntervalSinceReferenceDate: timestamp)
return .string(dateFormatter.string(from: date))
}
}
添加function配置:
func configure(_ app: Application) throws {
LeafEngine.entities.use(DataLeafFunction(), asFunction: "date")
// ...
}
在您的模板中使用此 function:
#date(date)
#date(date, "YY/MM/dd")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.