Skip to content

Commit fd925c2

Browse files
joelhawksleyJason Long
andcommitted
Slots return stripped HTML
While building a component that leveraged Slots, we ran into an issue where it was difficult to not introduce unintended whitespace in the rendered HTML for the component. This change strips the rendered HTML for slots, so that we don't end up with unintentional whitespace in the rendered output. Co-authored-by: Jason Long <[email protected]>
1 parent 1e9f430 commit fd925c2

File tree

4 files changed

+11
-2
lines changed

4 files changed

+11
-2
lines changed

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
# master
22

3+
* Slots return stripped HTML, removing leading and trailing whitespace.
4+
5+
*Jason Long, Joel Hawksley*
6+
37
# 2.16.0
48

59
* Add `--sidecar` option to the erb, haml and slim generators. Places the generated template in the sidecar directory.

coverage/coverage.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,4 @@ Incomplete test coverage
88
/lib/view_component/preview.rb: 94.0% (missed: 47,57,107)
99
/lib/view_component/render_to_string_monkey_patch.rb: 83.33% (missed: 9)
1010
/lib/view_component/test_helpers.rb: 91.67% (missed: 17,25)
11-
/test/view_component/integration_test.rb: 96.69% (missed: 14,15,16,18,20,365,366,367,369)
11+
/test/view_component/integration_test.rb: 96.73% (missed: 14,15,16,18,20,370,371,372,374)

lib/view_component/slotable.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ def slot(slot_name, **args, &block)
9898
slot_instance = args.present? ? slot_class.new(**args) : slot_class.new
9999

100100
# Capture block and assign to slot_instance#content
101-
slot_instance.content = view_context.capture(&block) if block_given?
101+
slot_instance.content = view_context.capture(&block).strip.html_safe if block_given?
102102

103103
if slot[:collection]
104104
# Initialize instance variable as an empty array

test/view_component/integration_test.rb

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -359,6 +359,11 @@ class IntegrationTest < ActionDispatch::IntegrationTest
359359
assert_select(".item.normal", count: 2)
360360

361361
assert_select(".footer.text-blue h3", text: "This is the footer")
362+
363+
title_node = Nokogiri::HTML.fragment(response.body).css(".title").to_html
364+
expected_title_html = "<div class=\"title\">\n <p>This is my title!</p>\n </div>"
365+
366+
assert_equal(title_node, expected_title_html)
362367
end
363368

364369
if Rails.version.to_f >= 6.1

0 commit comments

Comments
 (0)