Created
August 31, 2024 22:17
-
-
Save texpert/c4f1d95699b04b2a6c1eed9da9708eae to your computer and use it in GitHub Desktop.
svg_tag helper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
For a parametrized approach, you can add a helper into ApplicationHelper: | |
``` | |
def svg_tag(options = {}, class:) | |
tag.svg(xmlns: 'http://www.w3.org/2000/svg', class:, **options) do | |
yield if block_given? | |
end | |
end | |
``` | |
and then, use `svg_tag` in the views: | |
``` | |
<%= svg_tag({width: "16", height: "16", fill: "currentColor", viewBox: "0 0 16 16"}, class: "nav-icon bi bi-speedometer") do %> | |
'<path d="M8 2a.5.5 0 0 1 .5.5V4a.5.5 0 0 1-1 0V2.5A.5.5 0 0 1 8 2M3.732 3.732a.5.5 0 0 1 .707 0l.915.914a.5.5 0 1 1-.708.708l-.914-.915a.5.5 0 0 1 0-.707M2 8a.5.5 0 0 1 .5-.5h1.586a.5.5 0 0 1 0 1H2.5A.5.5 0 0 1 2 8m9.5 0a.5.5 0 0 1 .5-.5h1.5a.5.5 0 0 1 0 1H12a.5.5 0 0 1-.5-.5m.754-4.246a.39.39 0 0 0-.527-.02L7.547 7.31A.91.91 0 1 0 8.85 8.569l3.434-4.297a.39.39 0 0 0-.029-.518z"/>' + | |
'<path fill-rule="evenodd" d="M6.664 15.889A8 8 0 1 1 9.336.11a8 8 0 0 1-2.672 15.78zm-4.665-4.283A11.95 11.95 0 0 1 8 10c2.186 0 4.236.585 6.001 1.606a7 7 0 1 0-12.002 0"/>' | |
<% end %> | |
``` | |
Everything at all can be parametrized: | |
``` | |
<%= svg_tag({width: "16", height: "16", fill: "currentColor", viewBox: "0 0 16 16"}, class: "bi bi-speedometer") do %> | |
<%= tag.path(d: "M8 2a.5.5 0 0 1 .5.5V4a.5.5 0 0 1-1 0V2.5A.5.5 0 0 1 8 2M3.732 3.732a.5.5 0 0 1 .707 0l.915.914a.5.5 0 1 1-.708.708l-.914-.915a.5.5 0 0 1 0-.707M2 8a.5.5 0 0 1 .5-.5h1.586a.5.5 0 0 1 0 1H2.5A.5.5 0 0 1 2 8m9.5 0a.5.5 0 0 1 .5-.5h1.5a.5.5 0 0 1 0 1H12a.5.5 0 0 1-.5-.5m.754-4.246a.39.39 0 0 0-.527-.02L7.547 7.31A.91.91 0 1 0 8.85 8.569l3.434-4.297a.39.39 0 0 0-.029-.518z".html_safe) + | |
tag.path(fill_rule: "evenodd", d: "M6.664 15.889A8 8 0 1 1 9.336.11a8 8 0 0 1-2.672 15.78zm-4.665-4.283A11.95 11.95 0 0 1 8 10c2.186 0 4.236.585 6.001 1.606a7 7 0 1 0-12.002 0".html_safe) %> | |
<% end %> | |
``` | |
All of the above was just a mind exercise and saved here just in case it will be | |
necessary some day. | |
That said, the best way is like FontAwesome - having packed their SVG icons with | |
helpers to get them accessed. | |
Or, like Bootstrap Icons, providing their SVG in raw HTML - with 2 clicks they are | |
copied into the view. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment