📝

annotate_rendered_view_with_filenamesオプション

2021/02/19に公開
1

2022/3/25追記

templeにパッチが当たっていました。
https://github.com/judofyr/temple/pull/133
https://github.com/judofyr/temple/pull/134

さすがk0kubunさんですね 👀

本文

Railsでslim等のテンプレートエンジンを使っているプロジェクトも多いと思われる。

config.action_view.annotate_rendered_view_with_filenamesは、Railsが標準でサポートしているerbにしか適用されない。

slim等のテンプレートエンジンは別途対応が必要で、2021/2/19現在、slimでは本オプションが利用できない。
slimに該当の機能がないことが理由である。

雑にパッチを当ててみる

erbの実装を流用: https://github.com/rails/rails/blob/bf8c59cd896b1bf98d0f3df356531fa4c163219f/actionview/lib/action_view/template/handlers/erb.rb#L53-L56

# https://github.com/judofyr/temple/blob/v0.8.2/lib/temple/templates/rails.rb
$ diff rails.rb rails2.rb
8c8,17
<         self.class.compile((source || template.source), opts)
---
> 
>         result = '';
>         if ActionView::Base.annotate_rendered_view_with_filenames && template.format == :html
>           result << "@output_buffer.safe_concat('<!-- BEGIN #{template.short_identifier} -->');"
>         end
>         result << self.class.compile((source || template.source), opts)
>         if ActionView::Base.annotate_rendered_view_with_filenames && template.format == :html
>           result << ";@output_buffer.safe_concat('<!-- END #{template.short_identifier} -->');@output_buffer"
>         end
>         result

テストコード

# index.html.slim
= render 'a'
# _a.html.slim
.hoge
  p aaa

  = render 'b'
# _b.html.slim
.fuga
  p bbb

結果

※slimはデフォルトでインデントが設定されないが、便宜上インデントをつけた

<!-- BEGIN app/views/dashboards/_a.html.slim -->
<div class="hoge">
  <p>aaa</p>
  <!-- BEGIN app/views/dashboards/_b.html.slim -->
  <div class="fuga">
    <p>bbb</p>
  </div>
  <!-- END app/views/dashboards/_b.html.slim -->
</div>
<!-- END app/views/dashboards/_a.html.slim -->

Discussion

kehrakehra

@oboxodo
Thank you for your report.

I have only checked this with slim.
I didn't submit a Pull Request because I didn't know how much it would affect other gems.

My GitHub account is https://github.com/kehra .