簡體   English   中英

蒸汽從 postgres 傳遞數據到葉子模板

[英]Vapor pass data from postgres to a leaf template

我是蒸汽新手,

我嘗試將數據從postgres傳遞到leaf

routes.swift我有 function 來呈現葉子模板:

func routes(_ app: Application) throws {
    app.get("all") { req -> EventloopFuture<View> in
        let todos = Todo.query(on: req.db).all()

        let context = TodoContext(todos: todos)

        return req.view.render("index", context)
    }
}

但是我從上下文行中得到一個錯誤,它說無法將類型“EventLoopFuture<[Todo]>”的值轉換為預期的參數類型“[Todo]”。

如何將 EventLoopFuture<[Todo]> 轉換為 '[Todo]' 以便在上下文中使用它? 我在 query.all() 之后嘗試了 map function,但在此之后它仍然是 EventLoopFuture<[Todo]>。

TodoContext:

struct TodoContext: Content {
    let todos: [Todos]
}

東都 Model:

final class Todo: Model, Content {
    static let schema = "todo"
    
    @ID(key: .id)
    var id: UUID?

    @Field(key: "todo")
    var todo: String

    @Field(key: "complete")
    var complete: Bool

    init() { }

    init(id: UUID? = nil, todo: string, complete: Bool) {
        self.id = id
        self.todo = todo
        self.complete = complete
    }
}

你是正確的,你需要處理未來,但你應該使用flatMap因為渲染調用返回一個未來。 所以你的代碼應該是這樣的:

func routes(_ app: Application) throws {
    app.get("all") { req -> EventloopFuture<View> in
        return Todo.query(on: req.db).all().flatMap { todos in
          let context = TodoContext(todos: todos)
          return req.view.render("index", context)
      }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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