Rails中如何包含视图组件中的所有用户自定义辅助文件的方法是什么?

huangapple go评论63阅读模式
英文:

how is the rails way include all user custom helper files in view component

问题

class ApplicationViewComponent < ViewComponent::Base
  include ApplicationHelper
  include AllOtherUserCreatedHelperFiles
end

class FooComponent < ApplicationViewComponent
end
英文:
class ApplicationViewComponent &lt; ViewComponent::Base
  include ApplicationHelper
end

class FooComponent &lt; ApplicationViewComponent 
end 

How can I include not only ApplicationHelper but also user created all helper files in view component?

答案1

得分: 3

你不包括所有的辅助功能。

使用 helpers 代理来访问你的 Rails 辅助功能。

class UserComponent < ViewComponent::Base
  def profile_icon
    helpers.icon :user
  end
end

如果想简化调用,可以使用 delegate

class UserComponent < ViewComponent::Base
  delegate :icon, to: :helpers

  def profile_icon
    icon :user
  end
end

只在实际需要时包含辅助模块。

英文:

You don't include all the helpers.

Use the helpers proxy instead to access your Rails helpers.

class UserComponent &lt; ViewComponent::Base
  def profile_icon
    helpers.icon :user
  end
end

And use delegate if you want to simplify the calls:

class UserComponent &lt; ViewComponent::Base
  delegate :icon, to: :helpers

  def profile_icon
    icon :user
  end
end

Only include the helper modules when actually needed.

huangapple
  • 本文由 发表于 2023年2月16日 17:24:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75470161.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定