We have a web application written in Scala/Liftweb that is working well. Now we need to render some views/reports as PDF files. We already use libraries that will take well-formatted XHTML and output it as PDF so I'm attempting to get the output of a rendered Lift template as a string that I can feed into our PDF library.

How do I get the output of a template as a variable? I have seen this discussion where David Pollak talks about using S.render which returns a NodeSeq, but we're not making much progress on this front.

Ideally I'd do something like:

val seq = S.render(NodeSeq, ???)
val stringOutput = seq.toString()    
有帮助吗?

解决方案

If you do something like this, it should render the page:

val htmlString:Box[String] = for{
  r <- S.request
  t <- Templates("index" :: Nil)
} yield S.render(t, r.request))

Where index should be replaced by the path of the template you want to render. That should work for basic instances, but you'll need some additional work if you use Menu.params or other URL type variables.

Update:

If you need to access session objects outside of the HTTP request thread, you will need to initialize the session. To do so, you could modify the above like so:

val html = for{
  r <- S.request
  sn <- S.session 
  t <- Templates("index" :: Nil)
} yield S.initIfUninitted(sn) { 
  S.render(t, r.request)) 
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top