vapor / leaf

🍃 An expressive, performant, and extensible templating language built for Swift.

Home Page:https://docs.vapor.codes/4.0/leaf/getting-started

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Render to String

winsmith opened this issue · comments

I am trying to prepare email messages (sent via mailgun) and want to render them using Leaf as a template language. After some googling, I haven't really found a way to render templates into a string using Leaf 4, which would be ideal, because then I could render the emails on server and then pass them off to my email server.

I found #48 but the answer it gives is too sparse for me, and I'm not sure it applies any more.

Any ideas how I can accomplish this? I promise I'll even write a paragraph or two for the Vapor docs once I know the answer :D

You can do something like

request.view .render("template", context).map { view in
  let string = String(decoding: view.data.readableBytesView, as: UTF8.self)
}

Thanks! Okay, but I have to go through a view? Because I'm in a piece of code that is never rendered to a view because it gets run periodically. Is there a way to access the render method with just an Application? Played around with instantiating the LeafRenderer directly but got an EventLoopFuture<ByteBuffer> out of the render call that was never fulfilled.

(This might of course just be out of scope for Leaf, which is fine.)

But you are going through a view because that's what the Leaf renderer is. So you need to render a view to generate the string for an email or whatever use case.

You should be able to use app.view.render... in the same way

Ooh I get it now, I think I had some misconceptions there. Thank you very much!