SVG - fill color a variable

Instead of loading multiple SVGs of difference color but the same svg, I’d like to be able to swap out the fill color dynamically. How to do this please?

As I recall scripts don’t allow adjusting the CSS of an SVG loaded from a file, but if you embed it in a page then CSS can style it as normally and dynamically as you want? Nothing specific to phoenix, all normal HTML stuff. :slight_smile:

Maybe not a direct answer to the question but might give you some ideas :slight_smile:

In Dave Thomas’s excellent course…
https://codestool.coding-gnome.com/courses/elixir-for-programmers
there is a hangman game where parts of the hangman image opacity changes as the game goes along. This is done by putting EEX templating inside the SVG…

...
<path id="rope"
          style="<%= turn(@left, 6) %>; fill: #a28d5d; stroke: #a28d5d"
...

And the turn() function returns a different opacity depending on the arguments passed.

The image has a .hml.eex extension so that Phoneix will process it as any other templates.

That’s the conclusion I came to. Whatever you pass in will be available in the template using the @ prefix.

1 Like