Rails 6 基于Formtastic创建自定义Editor.js输入组件的问题
问题根因
as: :hidden不生效的原因:input_html_options方法返回的是输入标签的HTML属性集合,as是Formtastic用来声明输入组件类型的参数,不属于HTML属性,放在该方法中不会生效。- 无法添加额外div的原因:自定义Formtastic输入组件的完整渲染逻辑由
to_html方法控制,仅重写input_html_options只能修改输入标签本身的属性,无法追加额外的DOM元素。
正确实现代码
在Rails项目的app/inputs/editor_js_input.rb中写入以下代码:
class EditorJsInput < Formtastic::Inputs::HiddenInput # 重写渲染逻辑,拼接隐藏输入和editorjs容器 def to_html super + template.content_tag(:div, '', style: 'width: 100%; background: white;', id: 'editorjs' ) end # 仅修改隐藏输入的HTML属性 def input_html_options super.merge(id: 'editor_field') end end
注:直接继承
Formtastic::Inputs::HiddenInput就会默认渲染隐藏类型的输入框,不需要额外设置as: :hidden。
调用方式
在ActiveAdmin的表单配置中直接调用即可,无需再渲染局部模版:
<%= f.input :body, as: :editor_js %>
可选优化(避免同一页面多编辑器冲突)
如果同一个页面需要使用多个Editor.js实例,不要写死id,改为动态生成:
class EditorJsInput < Formtastic::Inputs::HiddenInput def to_html super + template.content_tag(:div, '', style: 'width: 100%; background: white;', id: "editorjs_#{method}" ) end def input_html_options super.merge(id: "editor_field_#{method}") end end
对应的JS逻辑中根据字段名匹配对应的id即可。
内容的提问来源于stack exchange,提问作者mr_muscle
相关产品推荐
相关产品推荐

