2023-10-01 rails 7.1でテンプレートに渡すローカル変数を定義できるようになった
syntaxちょっとキモいけどRails7.1のこの機能が便利だ » Rails 7.1 gives templates more control over the locals they receive | Shakacode https://t.co/JETg3xWv48
— toshimaru (@toshimaru_e) September 28, 2023
In Rails 7.1, developers can define or restrict local variables a template can accept. To implement this, you must add a local magic comment inside the template.
# app/views/shared/_payment_gateways.html.erb <%# locals: (paypal:, braintree:) -%>
ref. Rails 7.1 gives templates more control over the locals they receive | Shakacode
Rails PR
実装されたRailsのPRはこちら。
Before:
<%# issues/_card.html.erb %> <% title = local_assigns[:title] || "Default title" %> <% comment_count = local_assigns[:comment_count] || 0 %> <h2><%= title %></h2> <span class="comment-count"><%= comment_count %></span>
After:
<%# issues/_card.html.erb %> <%# locals: (title: "Default title", comment_count: 0) %> <h2><%= title %></h2> <span class="comment-count"><%= comment_count %></span>
結論
下記の理由からRails 7.1のこの機能は便利。
- テンプレートのローカル変数のデフォルト値を設定できる
- テンプレートに渡すローカル変数のバリデーションとして機能する