1
1

More than 1 year has passed since last update.

Railsのdraper decoratorでtagヘルパーを使いたい。例えばtag.span("hello")などと。

Last updated at Posted at 2022-05-23

やりたい事

Railsのdraperのdecoratorで、スマートにHTMLタグを生成したい。
今回は例えで"<span>hello</span>"をば。

"<span>hello</span>".html_safeでもできるけど、tagヘルパーを使ってもうちょいスマートに。

実装!

単にこう書いただけではエラーになる。

app/decorators/hello_decorator.rb
>> tag.span('hello')
=> undefined local variable or method 'tag' for #<HelloDecorator:0x00000000000> Did you mean?  tap

答え1

app/decorators/hello_decorator.rb
>> ApplicationDecorator.helpers.tag.span("hello")
=> "<span>hello</span>"

答え2

Draperのドキュメントをちゃんと読むと、もっと簡単に書けるらしい。
https://github.com/drapergem/draper#accessing-helpers

>> h.tag.span("hello")
=> "<span>hello</span>"

毎度ありがとうございます、 @Y_uuu さん。

1
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1