![](/img/trans.png)
[英]Vapor 3 - How to populate array property of model from Leaf template form
[英]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.