Skip to content

Commit 3f1b8a1

Browse files
committed
doc: update docs/leaf.md
1 parent 403e79b commit 3f1b8a1

1 file changed

Lines changed: 57 additions & 0 deletions

File tree

docs/leaf.md

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,12 @@ app.directory.viewsDirectory = "...."
5858
app.views.use(.leaf)
5959
```
6060

61+
配置自定义标签
62+
63+
```swift
64+
app.leaf.tags["relative"] = CustomTag()
65+
```
66+
6167
### 目录结构
6268

6369
```
@@ -223,6 +229,14 @@ return req.view.render("home",
223229
#endif
224230
```
225231

232+
多个条件满足时才渲染内容的模板
233+
234+
```html
235+
#if(title == "user" && count(users) > 0):
236+
You have users!
237+
#endif
238+
```
239+
226240
### #elseif
227241

228242
```html
@@ -469,6 +483,8 @@ return try await req.view.render(
469483
)
470484
```
471485

486+
自定义标签使用 `Data`
487+
472488
```swift
473489
struct NowTag: LeafTag {
474490
func render(
@@ -480,3 +496,44 @@ struct NowTag: LeafTag {
480496
```
481497

482498
`LeafContext` 包含两个重要的属性
499+
500+
### 相对路径拼接标签
501+
<!--rehype:wrap-class=col-span-2-->
502+
503+
```swift
504+
struct RelativePathTag: LeafTag {
505+
func render(_ ctx: LeafContext) throws -> LeafData {
506+
guard ctx.parameters.count == 1, let filename = ctx.parameters[0].string else {
507+
throw "Missing #relative parameters"
508+
}
509+
if let filepath = ctx.request?.url.path, filename.hasPrefix("/") == false {
510+
return .string("\(relativePrefix(for: filepath, targetFile: filename))")
511+
}
512+
return .string("\(filename)")
513+
}
514+
private func relativePrefix(for pagePath: String, targetFile: String) -> String {
515+
var components = pagePath
516+
.trimmingCharacters(in: CharacterSet(charactersIn: "/"))
517+
.split(separator: "/")
518+
if let last = components.last, last.contains(".") {
519+
components = components.dropLast()
520+
}
521+
let cleanTarget = targetFile.hasPrefix("./")
522+
? String(targetFile.dropFirst(2))
523+
: targetFile
524+
return String(repeating: "../", count: components.count) + cleanTarget
525+
}
526+
}
527+
```
528+
529+
配置标签
530+
531+
```swift
532+
app.leaf.tags["relative"] = RelativePathTag()
533+
```
534+
535+
现在可以在 Leaf 中使用我们的自定义标签了
536+
537+
```html
538+
<link rel="stylesheet" href="#relative("main.css")" />
539+
```

0 commit comments

Comments
 (0)