Skip to content

Commit

Permalink
Merge pull request #25 from vapor/html-escape
Browse files Browse the repository at this point in the history
add html escaping to string variables
  • Loading branch information
loganwright authored Oct 18, 2016
2 parents 3702616 + 4280514 commit ce2d27e
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 3 deletions.
11 changes: 11 additions & 0 deletions Sources/Leaf/HTMLEscape.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import Foundation

extension String {
func htmlEscaped() -> String {
return replacingOccurrences(of: "&", with: "&")
.replacingOccurrences(of: "\"", with: """)
.replacingOccurrences(of: "'", with: "'")
.replacingOccurrences(of: "<", with: "&lt;")
.replacingOccurrences(of: ">", with: "&gt;")
}
}
3 changes: 2 additions & 1 deletion Sources/Leaf/Node+Rendered.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ extension Node {
case let .number(number):
return number.description.bytes
case let .string(str):
return str.bytes
// defaults to escaping, use #raw(var) to unescape.
return str.htmlEscaped().bytes
case let .bytes(bytes):
return bytes
}
Expand Down
7 changes: 5 additions & 2 deletions Sources/Leaf/Tag/Models/Raw.swift
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
class Raw: Tag {
final class Raw: Tag {
let name = "raw"

func compileBody(stem: Stem, raw: String) throws -> Leaf {
Expand All @@ -7,8 +7,11 @@ class Raw: Tag {
}

func run(stem: Stem, context: Context, tagTemplate: TagTemplate, arguments: [Argument]) throws -> Node? {
return nil
guard let string = arguments.first?.value?.string else { return nil }
let unescaped = string.bytes
return .bytes(unescaped)
}

func shouldRender(stem: Stem, context: Context, tagTemplate: TagTemplate, arguments: [Argument], value: Node?) -> Bool {
return true
}
Expand Down
8 changes: 8 additions & 0 deletions Tests/LeafTests/RawTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,12 @@ class RawTests: XCTestCase {
let expectation = "Everything stays ##@$&"
XCTAssertEqual(rendered, expectation)
}

func testRawVariable() throws {
let raw = try stem.spawnLeaf(raw: "Hello, #raw(unescaped)!")
let context = Context(["unescaped": "<b>World</b>"])
let rendered = try stem.render(raw, with: context).string
let expectation = "Hello, <b>World</b>!"
XCTAssertEqual(rendered, expectation)
}
}

0 comments on commit ce2d27e

Please sign in to comment.