Iris: [QUESTION] If i use html template,How can I get response body(or HTML)? not use HttpRequest Client

Created on 19 Aug 2020  ·  4Comments  ·  Source: kataras/iris

If i use html template,How can I get response body(or HTML)? not use HttpRequest Client,do anyone kown it?

question

Most helpful comment

Thank you very much,I got it!

All 4 comments

Hello @caimingyi484,

You can already do that using the app.View method, after app.Build or Listen/Run. It accepts an io.Writer at its first argument, the rest parameters are the usual, the ones that ctx.View accepts.

In that io.Writer you can use w := new(bytes.Buffer) from standard import "bytes" package. Then w.String() to get its contents or w.Bytes() to get them as binary ([]byte). Actually there is an example which writes the template to the terminal(os.Stdout), take a look at: https://github.com/kataras/iris/blob/master/_examples/view/write-to/main.go

Let me write down a simple example for you:

import (
       "bytes"

       "github.com/kataras/iris/v12"
)

func main() {
        // Register the views.
    app.RegisterView(iris.HTML("./views", ".html"))

    // [YOUR ROUTES HERE....]


    // You need to call `app.Build` manually before using the `app.View` func,
    // so templates are built in that state.
        // If you are going to use `app.View` after `Listen` then you can SKIP this:
    app.Build()

    w := new(bytes.Buffer)
    err := app.View(w, "template.html", "layout.html", map[string]interface{}{
        "Title":    "This is my e-mail title",
        "Body":     "This is my e-mail body",
    })
        if err!=nil{
               app.Logger().Fatal(err)      
        }

       templateAsBytes := w.Bytes()
       // or
       templateAsString := w.String()
       // ...

       app.Listen(":8080")
}

And since you can do that, you can also do that from inside a Handler through ctx.Application().View.

Note that, if you are not going to use app.View from your main function, then you can remove the app.Build line.

func handler(ctx iris.Context){
        app := ctx.Application()

    w := new(bytes.Buffer)
    err := app.View(w, "template.html", "layout.html", map[string]interface{}{
        "Title":    "This is my e-mail title",
        "Body":     "This is my e-mail body",
    })
        if err!=nil {
               app.Logger().Warn(err)
               // [...handle error]      
        }

       templateAsBytes := w.Bytes()
       // or
       templateAsString := w.String()
       // ...
}

Please don't forget to star Iris, this is all we ask.

Have fun!
Gerasimos Maropoulos.

Thank you very much,I got it!

You are welcome @caimingyi484!

It seems this is solved :).

Was this page helpful?
0 / 5 - 0 ratings