簡體   English   中英

如何使用 Vapor 4 在 Leaf 模板中格式化日期字段

[英]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 日

不過,我還是不開心……

  1. 我想用 - 而不是 / 呈現它:星期三,2020 年 12 月 30 日

  1. 由於我的應用程序將被本地化,我想控制顯示日期的方式:Wed (Eng)、Mer(French)、Woe (Dutch) 那么如何設置應在 Leaf 中使用的區域設置? (我知道如何在 Vapor 中做到這一點,但如果可能的話,我寧願把它留給 Leaf。)

創建葉子方法:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM