fix(join): Dont force strings

This commit is contained in:
Kyle Fuller
2016-12-08 15:56:29 +00:00
parent 2331b11a52
commit 8f6b403aa9
3 changed files with 28 additions and 11 deletions

View File

@@ -47,17 +47,17 @@ func defaultFilter(value: Any?, arguments: [Any?]) -> Any? {
}
func joinFilter(value: Any?, arguments: [Any?]) throws -> Any? {
guard arguments.count == 1 else {
guard arguments.count < 2 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")
let separator = stringify(arguments.first ?? "")
if let value = value as? [Any] {
return value
.map(stringify)
.joined(separator: separator)
}
if let value = value as? [String] {
return value.joined(separator: separator)
}
return nil
return value
}

View File

@@ -125,9 +125,26 @@ func testFilter() {
describe("join filter") {
let template = Template(templateString: "{{ value|join:\", \" }}")
$0.it("transforms a string to be lowercase") {
$0.it("joins a collection of strings") {
let result = try template.render(Context(dictionary: ["value": ["One", "Two"]]))
try expect(result) == "One, Two"
}
$0.it("joins a mixed-type collection") {
let result = try template.render(Context(dictionary: ["value": ["One", 2, true, 10.5, "Five"]]))
try expect(result) == "One, 2, true, 10.5, Five"
}
$0.it("can join by non string") {
let template = Template(templateString: "{{ value|join:separator }}")
let result = try template.render(Context(dictionary: ["value": ["One", "Two"], "separator": true]))
try expect(result) == "OnetrueTwo"
}
$0.it("can join without arguments") {
let template = Template(templateString: "{{ value|join }}")
let result = try template.render(Context(dictionary: ["value": ["One", "Two"]]))
try expect(result) == "OneTwo"
}
}
}

View File

@@ -279,10 +279,10 @@ value of the variable. For example:
``join``
~~~~~~~~
Join an array with a string.
Join an array of items.
.. code-block:: html+django
{{ value|join:", " }}
.. note:: The value MUST be an array of Strngs and the separator must be a string.
.. note:: The value MUST be an array.