You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: README.md
+182
Original file line number
Diff line number
Diff line change
@@ -71,6 +71,188 @@ import SwiftHtml
71
71
72
72
That's it.
73
73
74
+
75
+
## Creating custom tags
76
+
77
+
You can define your own custom tags by subclassing the `Tag` or `EmptyTag` class.
78
+
79
+
You can follow the same pattern if you take a look at the core tags.
80
+
81
+
```swift
82
+
openclassDiv: Tag {
83
+
84
+
}
85
+
86
+
// <div></div> - standard tag
87
+
88
+
openclassBr: EmptyTag {
89
+
90
+
}
91
+
// <br> - no closing tag
92
+
93
+
```
94
+
95
+
By default the name of the tag is automatically derived from the class name (lowercased), but you can also create your own tag type & name by overriding the `createNode()` class function.
96
+
97
+
```swift
98
+
openclassLastBuildDate: Tag {
99
+
100
+
openoverrideclassfunccreateNode() -> Node {
101
+
Node(type: .standard, name: "lastBuildDate")
102
+
}
103
+
}
104
+
105
+
// <lastBuildDate></lastBuildDate> - standard tag with custom name
106
+
```
107
+
108
+
It is also possible to create tags with altered content or default attributes.
109
+
110
+
```swift
111
+
openclassDescription: Tag {
112
+
113
+
publicinit(_contents: String) {
114
+
super.init()
115
+
setContents("<![CDATA["+ contents +"]]>")
116
+
}
117
+
}
118
+
// <description><![CDATA[lorem ipsum]]></description> - content wrapped in CDATA
119
+
120
+
openclassRss: Tag {
121
+
122
+
publicinit(@TagBuilder _builder: () -> [Tag]) {
123
+
super.init(builder())
124
+
setAttributes([
125
+
.init(key: "version", value: "2.0"),
126
+
])
127
+
}
128
+
}
129
+
// <rss version="2.0">...</rss> - tag with a default attribute
130
+
```
131
+
132
+
## Attribute management
133
+
134
+
You can set, add or delete the attributes of a given tag.
staticfuncbuildExpression(_expression: [TagRepresentable]) -> Tag {
233
+
GroupTag {
234
+
expression.map { $0.build() }
235
+
}
236
+
}
237
+
}
238
+
```
239
+
240
+
Sometimes you'll need extra parameters for the build function, so you have to call the build method by hand.
241
+
242
+
In those cases it is recommended to introduce a `render` function instead of using build.
243
+
244
+
```swift
245
+
246
+
let tag =WebIndexTemplate(ctx) {
247
+
ListComponent(["a", "b", "c"])
248
+
.render(req)
249
+
}
250
+
.render(req)
251
+
```
252
+
253
+
If you want to create a lightweight template engine for the [Vapor](https://vapor.codes/) web framework using SwiftHtml, you can see a working example inside the [Feather CMS core](https://github.com/FeatherCMS/feather-core) repository.
0 commit comments