Skip to content

Support wrappers with multiple conditional components #56

@osjjames

Description

@osjjames

Is your feature request related to a problem? Please describe.

The existing wrapping functionality is great, but it's only applicable when the wrapper wraps a single component. Sometimes, a wrapper needs to depend on the presence of at least one of several components.

For example, consider a container element with a title and two components.

<div class="flex flex-col gap-4">
  <h3>Examples</h3>
  <div class="flex gap-2">
    <%= render ExampleA::Component %>
    <%= render ExampleB::Component %>
  </div>
</div>

If neither ExampleA or ExampleB render, then we don't want the wrapper to be rendered either (because it's missing its core content).

Describe the solution you'd like

I'd love some kind of syntax that would maintain the overall structure of the template code, but would mark the components as "conditional", i.e. the wrapper will not render if none of the "conditional" components are rendered.

This could be implemented as a special component, e.g. ShowIfWrapperComponent, which would look something like this:

<%= render ViewComponentContrib::ShowIfWrapperComponent.new do |wrapper| %>
  <div class="flex flex-col gap-4">
    <h3>Examples</h3>
    <div class="flex gap-2">
      <%= wrapper.show_if do %>
        <%= render ExampleA::Component %>
      <%- end -%>
      <%= wrapper.show_if do %>
        <%= render ExampleB::Component %>
      <%- end -%>
    </div>
  </div>
<%- end -%>

I've written an implementation for this component in #57.

Describe alternatives you've considered

I considered extending the existing ViewComponentContrib::WrappedComponent and its .wrapped helper to accept an array of components.

While this works functionally, it disrupts the structure of the template code, making it less readable. If any of the components have slots, the template code becomes even more convoluted. The above solution allows for the template code to flow normally with a small amount of additional syntax.

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions