How to render component with slots that accept HTML? #624
-
Hey team! I'm playing around with Lookbook and I ran into an issue I'm not sure how to solve. What's the best way to write a preview for a component that is used like this? <%= render DisclosureComponent.new(title: "Open disclosure") do %>
<h2>This goes inside the disclosure</h2>
<p>It can be a multi-line block of HTML with multiple tags</p>
<% end %> class DisclosureComponentPreview
def default
render DisclosureComponent.new(title: "Open disclosure") do
# how should I write markup here?
end
end
end I looked for references in the docs and in the example lookbook app but all of them use a simple string as the block content. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hi @pinzonjulian, There are a number of ways to add markup to the component block content when rendering previews. One thing to keep in mind whichever method you use is that when in a Ruby context and not in a template (ERB) context only the last line of the block will be used as the block content (just like the implict return value in Ruby methods). The simplest way is probably to add markup as a string and tag it as .html_safe` like this: class DisclosureComponentPreview
def default
render DisclosureComponent.new(title: "Open disclosure") do
"<h2>This goes inside the disclosure</h2><p>It can be a multi-line block of HTML with multiple tags</p>".html_safe
end
end
end (You could always use heredoc syntax to make multiline content look a bit nicer if you wanted to.) The other way is to use Rails' tag builder helpers to generate the HTML: class DisclosureComponentPreview
def default
render DisclosureComponent.new(title: "Open disclosure") do
safe_join([
tag.h2("This goes inside the disclosure"),
tag.p("It can be a multi-line block of HTML with multiple tags")
])
end
end
end In this example I've used But, if you have components that you want to preview with large amounts of markup then probably the best way is to use a preview template to render the component in and ERB template. This is usually much closer to how the component will actually be used in the real world. Hopefully that all makes sense! |
Beta Was this translation helpful? Give feedback.
Hi @pinzonjulian,
There are a number of ways to add markup to the component block content when rendering previews.
One thing to keep in mind whichever method you use is that when in a Ruby context and not in a template (ERB) context only the last line of the block will be used as the block content (just like the implict return value in Ruby methods).
The simplest way is probably to add markup as a string and tag it as .html_safe` like this:
(…