如何在资产管道中包含 ActionView 助手?

问题描述:

如何包含 Rails 视图助手以便资产管道执行上下文可以访问?

How to include Rails view helpers to be accesible by assets pipeline execution context?

一个示例用例是使用 form_tag 辅助方法为表单生成标记,并使其可用于 Javascript 模板(如把手、jst 等).

An example use case would be to generate the markup for a form, using form_tag helper method, and make it available to a Javascript template (like handlebars, jst, etc.).

我使用 handlebar_assets gem,但这也适用于任何 erbhaml 模板.

I use handlebar_assets gem, but this should apply to any erb or haml template too.

创建一个初始化程序并在资产的上下文中包含帮助程序,如下所示:

Create a inititializer and include the helpers in the context of the assets like this:

Rails.application.assets.context_class.class_eval do
  include ActionView::Helpers
  include MyAppHelper
  include Rails.application.routes.url_helpers
end

取自这个链轮问题