简体   繁体   中英

Vapor pass data from postgres to a leaf template

I'm new to Vapor,

I try to pass data from postgres to leaf .

In the routes.swift I have the function to render the leaf template:

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)
    }
}

But I get an Error from the context line, it says Cannot convert value of type 'EventLoopFuture<[Todo]>' to expected argument type '[Todo]'.

How do I convert a EventLoopFuture<[Todo]> to '[Todo]' so I can use it in the context? I try the map function after query.all(), but after this its still a EventLoopFuture<[Todo]>.

The TodoContext:

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

The Todo 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
    }
}

You're correct in that you need to handle the future but you should use flatMap since the render call returns a future. So your code should look like:

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)
      }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM