feat(filters): Add a join filter
This commit is contained in:
@@ -18,6 +18,12 @@
|
||||
Hello {{ name|default:"World" }}
|
||||
```
|
||||
|
||||
- There is now a `join` filter.
|
||||
|
||||
```html+django
|
||||
{{ value|join:", " }}
|
||||
```
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
- Variables (`{{ variable.5 }}`) that reference an array index at an unknown
|
||||
|
||||
@@ -35,3 +35,19 @@ func lowercase(_ value: Any?) -> Any? {
|
||||
func defaultFilter(value: Any?, arguments: [Any?]) -> Any? {
|
||||
return value ?? arguments.first as Any
|
||||
}
|
||||
|
||||
func joinFilter(value: Any?, arguments: [Any?]) throws -> Any? {
|
||||
guard arguments.count == 1 else {
|
||||
throw TemplateSyntaxError("'join' filter takes a single argument")
|
||||
}
|
||||
|
||||
guard let separator = arguments.first as? String else {
|
||||
throw TemplateSyntaxError("'join' filter takes a separator as string")
|
||||
}
|
||||
|
||||
if let value = value as? [String] {
|
||||
return value.joined(separator: separator)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -49,6 +49,7 @@ public class Namespace {
|
||||
registerFilter("capitalize", filter: capitalise)
|
||||
registerFilter("uppercase", filter: uppercase)
|
||||
registerFilter("lowercase", filter: lowercase)
|
||||
registerFilter("join", filter: joinFilter)
|
||||
}
|
||||
|
||||
/// Registers a new template tag
|
||||
|
||||
@@ -103,4 +103,13 @@ func testFilter() {
|
||||
try expect(result) == "Hello World"
|
||||
}
|
||||
}
|
||||
|
||||
describe("join filter") {
|
||||
let template = Template(templateString: "{{ value|join:\", \" }}")
|
||||
|
||||
$0.it("transforms a string to be lowercase") {
|
||||
let result = try template.render(Context(dictionary: ["value": ["One", "Two"]]))
|
||||
try expect(result) == "One, Two"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -130,3 +130,14 @@ value of the variable. For example:
|
||||
.. code-block:: html+django
|
||||
|
||||
Hello {{ name|default:"World" }}
|
||||
|
||||
``join``
|
||||
~~~~~~~~
|
||||
|
||||
Join an array with a string.
|
||||
|
||||
.. code-block:: html+django
|
||||
|
||||
{{ value|join:", " }}
|
||||
|
||||
.. note:: The value MUST be an array of Strngs and the separator must be a string.
|
||||
|
||||
Reference in New Issue
Block a user