Set the default CSS class for Rails form builder helper methods

I'm looking for a general way to apply some external CSS frameworks in a Rails application. These structures typically define the set of class names that should be used for certain HTML elements.

Consider the jQuery UI. To achieve a consistent form style, you would want something like this:

# in a view <% form_for @foo do |f| %> ... <%= f.text_field :bar, :class => ['ui-widget', 'ui-widget-content', 'ui-widget-container', 'ui-corner-all'] %> or <%= f.text_field :bar, :class => 'ui-widget ui-widget-content ui-widget-container ui-corner-all' %> <% end %> 

Doing this for each input field is not DRY at all.

Even a helper method, for example

 # in application_helper.rb def jquery_ui_classes 'ui-widget ui-widget-content ui-widget-container ui-corner-all' end # in a view <%= f.text_field :bar, :class => jquery_ui_classes %> 

or

 # in application_helper.rb def jquery_text_field(form_builder, method, opts = {}) ui = ['ui-widget', 'ui-widget-content', 'ui-widget-container', 'ui-corner-all'] klass = [opts.delete(:class), ui].flatten.compact form_builder.text_field method opts.merge(:class => klass) end # in a view <%= jquery_text_field f, :bar %> 

doesn't look right (or more DRY) since you still have to touch the generated form view ...

Alternative methods can now be the beheading of the InstanceTag class or hack the form_for .

Has anyone done this before?

By the way, I would not use jQuery (or Javascript at all) to apply class attributes, since JS can be disabled or blocked or even delivered with a delay and cause flickering ...

Cheers
Dominik

+6
source share
1 answer

https://github.com/phallstrom/form_helper_css

You cannot specify the classes you want, but it will add reasonable class names to all inputs so you can easily configure them (in all browsers).

0
source

Source: https://habr.com/ru/post/891685/


All Articles