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
- Host: GitHub
- URL: https://github.com/qichunren/view_context
- Owner: qichunren
- License: mit
- Created: 2022-03-24T15:20:43.000Z (about 4 years ago)
- Default Branch: main
- Last Pushed: 2022-03-24T15:51:46.000Z (about 4 years ago)
- Last Synced: 2025-04-05T10:31:26.178Z (about 1 year ago)
- Topics: actionview-component, rails, rails-helper
- Language: Ruby
- Homepage:
- Size: 4.88 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
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,:
<% 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| %>
<%= link_to post_category.name, admin_posts_path(category: post_category.id) %>
<% 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 %>
```