Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call functions from a .eex file

I'm trying to learn Phoenix, and ran into a question. In Rails I could say

<%= Rails.version %>

to get the current rails version displayed in a .erb file. I asked about how to do this in Phoenix, and got the answer

:application.get_key(:phoenix, :vsn)

Unfortunately, this highlights my ignorance as I try to ramp up with Phoenix. When I put

<%= :application.get_key(:phoenix, :vsn) %>

in my .eex file, I get

no function clause matching in Phoenix.HTML.Safe.Tuple.to_iodata/1

Please point me to any docs that help me to learn what to try next. Thank you!

like image 876
Daniel Ashton Avatar asked Oct 05 '15 20:10

Daniel Ashton


1 Answers

The :application.get_env call returns a tuple in the format:

{:ok, '1.0.0'}

Phoenix.HTML.Safe does not have a function to decode a tuple in this format (source). You will need to extract the version from the call:

<%= :application.get_key(:phoenix, :vsn) |> elem(1) %>

However a better way would be to use a helper function:

defmodule VersionHelper do
  def version do
    case :application.get_key(:phoenix, :vsn) do
      {:ok, vsn} -> vsn
      _          -> #raise or return null or something else
    end
  end
end

This can then be called in your view with VersionHelper.version - this means that your fetching of the version is not tied to the key that phoenix uses in the view.

like image 172
Gazler Avatar answered Oct 22 '22 19:10

Gazler