Overload Phoenix.HTML.Safe for list of floats

Phoenix won’t directly print a list of floats on a page

there is already a Phoenix.HTML.Safe protocol for lists but the list of floats are excluded

is it possible to overload only that specific part of the protocol to add a special formatting for a list of floats (representing some coordinates) ?

or is it mandatory to build a new ecto type ?

You could create a small view function that takes a list of floats and turns them into a string and call that from your template. You will then get control over how they are displayed (e.g. decimal places).

This is the general pattern - things like maps and tuples also need specific rendering helper functions in your views.


Helpers methods in your views is the way to go as by previous response.

I needed same for my charting and I was lazy so I just called Jason.encode(floatlist)

yes but I get the array of float from a text input in a form and I would like the changeset to reflect the correct value without tweaking when the form comes back

for a field f1 which is {:array, :float}
I use 45 / 56 in the form to get [45.0, 56.0] after ad hoc parsing but then the value does not print back in the form because array of floats…
<%= text_input f, :f1 %> fails
I would need to add value: small_function(f.data.f1) but I would like it to be automatic through specific type maybe

Well your issue is not printing floats. It is your form structure.

Your should have in your form

for value <- myArray
number_input numbers ... name: myArray[] value: value

You will receive an array of strings in your myArray

Your changeset should cast them to float for you.

I did that before, but I want only one text field for the components of the array and parse them from a string,
for more compactness in the user interface

once the changeset get the parsed floats values it cannot print back in the form unless maybe using some ecto type, or a specific protocol , or manually tweaking with value: some_formatting(data)

yes in your use case the available option is that and you will have the cater for parsing incoming value as an array too.

so there is no other option ?
not possible to add a Phoenix.HTML.Safe impl for this specific case ?

with a specific ecto type I can get automatic parsing on read with the cast callback from the text input field, but I cannot print it back in the form field without ad hoc formatting

You absolutely could but seems like an overkill. If you have the need go for it.

AFAIK you can not, HTML forms can do so much