Django
Django 是由 flosch 创建的模板引擎,查看原始语法文档请点击此处
基本示例
./views/index.django
{% include "partials/header.django" %}
<h1>{{ Title }}</h1>
{% include "partials/footer.django" %}
./views/partials/header.django
<h2>Header</h2>
./views/partials/footer.django
<h2>Footer</h2>
./views/layouts/main.django
<!DOCTYPE html>
<html>
<head>
<title>Main</title>
</head>
<body>
{{embed}}
</body>
</html>
package main
import (
"log"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/template/django/v3"
)
func main() {
// Create a new engine
engine := django.New("./views", ".django")
// Or from an embedded system
// See github.com/gofiber/embed for examples
// engine := html.NewFileSystem(http.Dir("./views", ".django"))
// 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, World!",
})
})
app.Get("/layout", func(c *fiber.Ctx) error {
// Render index within layouts/main
return c.Render("index", fiber.Map{
"Title": "Hello, World!",
}, "layouts/main")
})
log.Fatal(app.Listen(":3000"))
}
使用嵌入式文件系统 (仅限 1.16+)
使用 // go:embed
指令时,当使用 django.NewFileSystem()
实例化模板引擎时,使用 django 的 {% extend '' %}
关键字解析继承模板会失败。在这种情况下,请使用 django.NewPathForwardingFileSystem()
函数来实例化模板引擎。
此函数提供了用于解析继承模板的正确配置。
假设你有以下文件
然后
package main
import (
"log"
"embed"
"net/http"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/template/django/v3"
)
//go:embed views
var viewsAsssets embed.FS
func main() {
// Create a new engine
engine := NewPathForwardingFileSystem(http.FS(viewsAsssets), "/views", ".django")
// Pass the engine to the Views
app := fiber.New(fiber.Config{
Views: engine,
})
app.Get("/", func(c *fiber.Ctx) error {
// Render descendant
return c.Render("descendant", fiber.Map{
"greeting": "World",
})
})
log.Fatal(app.Listen(":3000"))
}
注册和使用自定义函数
// My custom function
func Nl2brHtml(value interface{}) string {
if str, ok := value.(string); ok {
return strings.Replace(str, "\n", "<br />", -1)
}
return ""
}
// Create a new engine
engine := django.New("./views", ".django")
// register functions
engine.AddFunc("nl2br", Nl2brHtml)
// Pass the engine to the Views
app := fiber.New(fiber.Config{Views: engine})
在 handler 中
c.Render("index", fiber.Map{
"Fiber": "Hello, World!\n\nGreetings from Fiber Team",
})
./views/index.django
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"></head>
<body>
{{ nl2br(Fiber) }}
</body>
</html>
输出
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"></head>
<body>
Hello, World!<br /><br />Greetings from Fiber Team
</body>
</html>
模板数据绑定的重要信息
使用 Pongo2 和此模板引擎时,了解数据绑定的特定规则至关重要。只支持与以下正则表达式匹配的键:^[a-zA-Z0-9_]+$
。
这意味着包含特殊字符或标点符号的键,例如 my-key
或 my.key
,是不兼容的,并且不会绑定到模板。这是由底层的 Pongo2 模板引擎强制执行的限制。请确保你的键遵循这些规则,以避免任何绑定问题。
如果需要在模板中访问不符合 Pongo2 模板引擎键命名限制的值,可以在调用 fiber.Render
时将该值绑定到一个新字段。示例如下
c.Render("index", fiber.Map{
"Fiber": "Hello, World!\n\nGreetings from Fiber Team",
"MyKey": c.Locals("my-key"),
})
### AutoEscape is enabled by default
When you create a new instance of the `Engine`, the auto-escape is **enabled by default**. This setting automatically escapes output, providing a critical security measure against Cross-Site Scripting (XSS) attacks.
### Disabling Auto-Escape
Auto-escaping can be disabled if necessary, using the `SetAutoEscape` method:
```go
engine := django.New("./views", ".django")
engine.SetAutoEscape(false)
使用 Django 内置模板标签设置 AutoEscape
- 显式关闭某个部分的自动转义
{% autoescape off %}
{{ "<script>alert('Hello World');</script>" }}
{% endautoescape %}
- 重新开启某个部分的自动转义
{% autoescape on %}
{{ "<script>alert('Hello World');</script>" }}
{% endautoescape %}
- 也可以使用 safe 内置过滤器针对每个变量进行设置
<h1>{{ someSafeVar | safe }}</h1>
{{ "<script>" | safe }}
禁用自动转义的安全隐患
禁用自动转义应谨慎处理。这可能使你的应用程序面临 XSS 攻击,即恶意脚本被注入到网页中。如果没有自动转义,存在从用户提供的数据中渲染有害 HTML 或 JavaScript 的风险。
建议保持自动转义启用状态,除非有充分理由禁用它。如果确实禁用,请确保所有用户提供的内容都经过彻底的净化和验证,以避免 XSS 漏洞。