Skip to content

Commit ecc66e8

Browse files
authored
Merge pull request #2511 from ViewComponent/2483-translation-fix
Allow I18n calls in render?
2 parents a3b9af5 + d69f177 commit ecc66e8

File tree

4 files changed

+30
-2
lines changed

4 files changed

+30
-2
lines changed

docs/CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,10 @@ nav_order: 6
1010

1111
## main
1212

13+
* Allow I18n calls in `render?`.
14+
15+
*23tux*
16+
1317
* ViewComponent now works without `rails` and `railties` gems loaded, enabling compatibility with Bridgetown 2.0.
1418

1519
*Tom Lord*

lib/view_component/base.rb

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -131,15 +131,14 @@ def render_in(view_context, &block)
131131

132132
@__vc_content_evaluated = false
133133
@__vc_render_in_block = block
134+
@view_context.instance_variable_set(:@virtual_path, virtual_path)
134135

135136
before_render
136137

137138
if render?
138139
value = nil
139140

140141
@output_buffer.with_buffer do
141-
@view_context.instance_variable_set(:@virtual_path, virtual_path)
142-
143142
rendered_template =
144143
around_render do
145144
render_template_for(@__vc_requested_details).to_s

test/sandbox/config/locales/en.yml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,3 +24,7 @@ en:
2424

2525
my_component:
2626
message: "OH NO! (you shouldn't see me)"
27+
28+
rendering_test:
29+
i18n_test_component:
30+
message: "I can be called in render?"

test/sandbox/test/rendering_test.rb

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1344,4 +1344,25 @@ def test_render_partial_with_yield_and_method_call
13441344
render_inline(PartialWithYieldAndMethodCallComponent.new)
13451345
assert_text "hello world", exact: true, normalize_ws: true
13461346
end
1347+
1348+
class I18nTestComponent < ViewComponent::Base
1349+
def message
1350+
t(".message")
1351+
end
1352+
1353+
def render?
1354+
message
1355+
end
1356+
1357+
def call
1358+
content_tag :div, t(".message")
1359+
end
1360+
end
1361+
1362+
def test_i18n_in_render_hook
1363+
vc_test_request.params[:hello] = "world"
1364+
render_inline(I18nTestComponent.new)
1365+
1366+
assert_selector("div", text: I18n.t("rendering_test.i18n_test_component.message"))
1367+
end
13471368
end

0 commit comments

Comments
 (0)