Description
First of all, really starting to enjoy Phlex - I think you may be onto the something here 👍
This is an idea that was borne out of my desire (need?) to automatically modify certain attributes of any HTML tag. Primarily, I want to be able to "rewrite" class names to support CSS modules. But this could be used for any attribute with simple and quite advanced uses.
Define an #[name]_attribute
method in your view, and then any attribute in that view will be processed through this method.
So as a first trivial example, I want to be able to pass an array of class names instead of a string (yes I know I can use the classes
or token
helpers, but I want to save keystrokes - I don't have many left 😜).
class HeaderView < Phlex::View
# Returns <div class="some class names"></div>
def template
div class: ['some', 'class', 'names']
end
def class_attribute(value)
value.join ' '
end
end
The class_attribute
method receives the value given in template
(['some', 'class', 'names']
), and returns the result of joining the array. But of course, it could do absolutely anything.
Any method that begins with an attribute name and ends with _attribute
, can be used to "massage" that attributes value. not convinced on the naming here, but it's a start.
There is also some scope here to specify which tags an attribute method should be applied to, perhaps like this:
def class_attribute(value, tag)
value.join ' ' if tag == :div
end
Anyway, this is just an idea, but also a simple one that would need a very small change to Phlex::View#_build_atttibutes
:
# ...
if respond_to?(:"#{k}_attribute")
v = send :"#{k}_attribute", v
end
# ...
Thoughts?