feat(filters): Add a join filter

This commit is contained in:
Kyle Fuller
2016-11-27 19:47:50 +00:00
parent dfd57e9571
commit 9fdbbc99e9
5 changed files with 43 additions and 0 deletions

View File

@@ -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

View File

@@ -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
}

View File

@@ -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

View File

@@ -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"
}
}
}

View File

@@ -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.