An open API service indexing awesome lists of open source software.

https://github.com/qichunren/view_context

Enhance Rails partial template capability with a simple way
https://github.com/qichunren/view_context

actionview-component rails rails-helper

Last synced: 30 days ago
JSON representation

Enhance Rails partial template capability with a simple way

Awesome Lists containing this project

README

          

# ViewContext

Rails view helper [render](https://guides.rubyonrails.org/layouts_and_rendering.html#using-partials-to-simplify-views) method is not easy to render complicated layout html partial.

ViewContext is a tiny helper class to enhance Rails partial template capability with a simple way.

[view_component](https://github.com/github/view_component) maybe not a necessary dependency if you just want to keep simple.

No gem, just add [view_context.rb](https://github.com/qichunren/view_context/blob/main/view_context.rb) to your Rails project autload path.

## Demo usage

Render a tailwindcss tab html snippet for example.

```html
# _tab.html.erb




    <%= yield %>


<%= side %>

```

And use the partial in a page in general,:

```html
<%= render "shared/tab", side: "".html_safe do %>

  • Tab 1

  • Tab 2

  • Tab 3

  • <% end %>
    ```

    Now with [ViewContext](https://github.com/qichunren/view_context/blob/main/view_context.rb) helper class, things became simple and flexible.

    First, change a little in _tab.html.erb partial:

    ```
    <% _view_context = ViewContext.new(self) %>



      <%= yield _view_context %>
      <%= _view_context.main %>

    <%= _view_context.side %>

    ```

    Then, render tab template partial below:

    ```html
    <%= render "shared/tab" do |context| %>

    <% context.set_main do %>
    <% PostCategory.all.each do |post_category| %>


    <% end %>
    <% end %>

    <% context.set_side do %>
    <%= link_to admin_post_categories_path do %>
    <%= heroicon "cog", options: { class: "w-4 h-4 text-primary-500 mr-2" } %>
    <% end %>
    <% end %>

    <% end %>
    ```