iris icon indicating copy to clipboard operation
iris copied to clipboard

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

Open caimingyi484 opened this issue 5 years ago • 4 comments

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

caimingyi484 avatar Aug 19 '20 02:08 caimingyi484

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.

kataras avatar Aug 19 '20 03:08 kataras

Thank you very much,I got it!

caimingyi484 avatar Aug 19 '20 07:08 caimingyi484

You are welcome @caimingyi484!

kataras avatar Aug 19 '20 11:08 kataras

It seems this is solved :).

AlbinoGeek avatar Sep 13 '20 20:09 AlbinoGeek