Skip to content

Commit

Permalink
Add inlineHTML method.
Browse files Browse the repository at this point in the history
  • Loading branch information
jverkoey committed Sep 16, 2024
1 parent 04bbf0a commit 9bcf379
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
20 changes: 20 additions & 0 deletions Sources/Slipstream/Rendering/Render.swift
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,23 @@ public func renderHTML(_ view: any View) throws -> String {
try view.render(document, environment: EnvironmentValues())
return try document.html()
}

/// Renders the given view as an HTML document and returns the HTML.
///
/// This is a non-throwing alternative to ``renderHTML(_:)`` that can be used more easily in
/// string concatenation, such as ``MarkdownText`` content.
///
/// Note that this method creates a new environment context.
///
/// - Parameter builder: A block that constructs the view or set of views to be rendered.
/// - Returns: The generated and formatted HTML string. If an error occurs during rendering, then the
/// error will be returned as an HTML comment.
public func inlineHTML<Content: View>(@ViewBuilder _ builder: () -> Content) -> String {
let document = Document("/")
do {
try builder().render(document, environment: EnvironmentValues())
return try document.html()
} catch let error {
return "<!-- \(error) -->"
}
}
21 changes: 21 additions & 0 deletions Tests/SlipstreamTests/Rendering/InlineHTMLTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import Foundation
import Testing

import Slipstream

final class InlineHTMLTests {

@Test func stringConcatenation() async throws {
#expect("""
This is some text.
\(inlineHTML {
Text("Foo")
})
""" == """
This is some text.
<p>Foo</p>
""")
}
}

0 comments on commit 9bcf379

Please sign in to comment.