Ziggy for Vapor

一种更好的组织路由的方式。

Swift Version Vapor Version GitHub license

安装

Ziggy 添加到你的 package 依赖项(在你的 Package.swift 文件中)

dependencies: [
    ...,
    .package(url: "https://github.com/m1guelpf/ziggy-vapor.git", from: "1.0.0")
]

以及添加到你的 target(例如 "App")

targets: [
    ...
    .target(
        name: "App",
        dependencies: [... "Ziggy" ...]
    ),
    ...
]

开始使用 🚀

在你的 configure.swift 文件中导入 Ziggy,然后调用 setup 方法

// Sources/App/configure.swift
import Ziggy

// configures your application
public func configure(_ app: Application) async throws {
    // ...

    app.ziggy.setup()

    // ...
}

然后,在你的 routes.swift 文件(或者任何你定义路由的地方),你可以将 name 方法链接到你的路由,为它们命名

// Sources/App/routes.swift
import Vapor
import Ziggy

public func routes(_ app: Application) throws {
    app.get { req in
        return req.view.render("dashboard")
    }.name("dashboard")

    // ...
}

你可以使用 app.route(或 req.route)函数为你的路由生成 URL

let url = app.route("home") // /dashboard
let edit_user = req.route("users.edit", 1) // /users/1/edit

return req.redirect(route: "user.profile", "m1guelpf") // Redirects to /@m1guelpf

你也可以在你的前端访问 route 函数,通过将 routes 标签添加到你的 HTML 模板并安装 ziggy-js

<!doctype html>
<html lang="en">
	<head>
		<meta charset="utf-8">
        <link rel="stylesheet" href="/app.css" />
        <script type="module" src="/app.js"></script>

		#routes()
	</head>

	<body>
		<!-- ... -->
	</body>
</html>

📄 许可协议

此软件包是根据 MIT 许可证 授权的开源软件