How to use the method of pongo2 registerfilter?
Closed this issue · 3 comments
pianchi commented
`
import (
"github.com/flosch/pongo2"
)
pongo2.RegisterFilter("nl2br", Nl2brHtml)
func Nl2brHtml(in *pongo2.Value, param *pongo2.Value) (out *pongo2.Value, err *pongo2.Error) {
if !in.IsString() {
s3 := " "
return pongo2.AsValue(s3), nil
} else {
s1 := in.String()
s2 := strings.Replace(s1, "\n", "<br />", -1)
return pongo2.AsValue(s2), nil
}
}`
{{"mytext" | nl2br }}ReneWerner87 commented
Here an example for this
package main
import (
"log"
"strings"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/template/django"
)
func Nl2brHtml(value interface{}) string {
if str, ok := value.(string); ok {
return strings.Replace(str, "\n", "<br />", -1)
}
return ""
}
func main() {
// Create a new engine
engine := django.New("./views", ".django")
engine.AddFunc("nl2br", Nl2brHtml)
// Pass the engine to the Views
app := fiber.New(fiber.Config{Views: engine})
app.Get("/", func(c *fiber.Ctx) error {
// Render index
return c.Render("index", fiber.Map{
"Title": "Hello,\n\n World!",
})
})
log.Fatal(app.Listen(":3000"))
}
views/index.django
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
Title: {{ nl2br(Title) }}
</body>
</html>
Output:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
Title: Hello,<br /><br /> World!
</body>
</html>
Unfortunately it is not as intuitive as you would think, we will add an example
do you(@pianchi ) have any other questions? otherwise i would close the issue
ReneWerner87 commented
ReneWerner87 commented
Since there is no further message, I assume that the issue is done and can be closed.
if you have any questions, please feel free to open the issue again