feat: added split fitler (#187)
This commit is contained in:
@@ -7,6 +7,7 @@
|
||||
- Added support for resolving superclass properties for not-NSObject subclasses
|
||||
- The `{% for %}` tag can now iterate over tuples, structures and classes via
|
||||
their stored properties.
|
||||
- Added `split` filter
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
|
||||
@@ -57,6 +57,7 @@ class DefaultExtension: Extension {
|
||||
registerFilter("uppercase", filter: uppercase)
|
||||
registerFilter("lowercase", filter: lowercase)
|
||||
registerFilter("join", filter: joinFilter)
|
||||
registerFilter("split", filter: splitFilter)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -40,3 +40,16 @@ func joinFilter(value: Any?, arguments: [Any?]) throws -> Any? {
|
||||
|
||||
return value
|
||||
}
|
||||
|
||||
func splitFilter(value: Any?, arguments: [Any?]) throws -> Any? {
|
||||
guard arguments.count < 2 else {
|
||||
throw TemplateSyntaxError("'split' filter takes a single argument")
|
||||
}
|
||||
|
||||
let separator = stringify(arguments.first ?? " ")
|
||||
if let value = value as? String {
|
||||
return value.components(separatedBy: separator)
|
||||
}
|
||||
|
||||
return value
|
||||
}
|
||||
|
||||
@@ -183,4 +183,20 @@ func testFilter() {
|
||||
try expect(result) == "OneTwo"
|
||||
}
|
||||
}
|
||||
|
||||
describe("split filter") {
|
||||
let template = Template(templateString: "{{ value|split:\", \" }}")
|
||||
|
||||
$0.it("split a string into array") {
|
||||
let result = try template.render(Context(dictionary: ["value": "One, Two"]))
|
||||
try expect(result) == "[\"One\", \"Two\"]"
|
||||
}
|
||||
|
||||
$0.it("can split without arguments") {
|
||||
let template = Template(templateString: "{{ value|split }}")
|
||||
let result = try template.render(Context(dictionary: ["value": "One, Two"]))
|
||||
try expect(result) == "[\"One,\", \"Two\"]"
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user