Paulo Janeiro
Paulo Janeiro

Reputation: 3221

Unable to pass correctly an argument in a template

I have this inside "web/templates/module/headerHC.html.eex":

   <%= for element <- MyProject.PageView.Recursion.buildElements(@header_linkNumber),1) do %>
            <%= element %>
   <% end %>

Then, I use this component in "web/layout/HC.html.eex":

<%= render FabricaASA.ModuleView, "headerHC.html", conn: @conn,
    header_class: nil,
    header_linkNumber: "3"
%>

Finally I've defined inside "web/views/page_view.ex":

defmodule Recursion do
        def buildElements(n) when n <= 1 do
            [n]
        end
        def buildElements(n) do
            [n | buildElements(n - 1)]
        end
    end

The problem is that I'm getting this error:

bad argument in arithmetic expression pointing to this line:

def buildElements(n) when n <= 1 do

This happens when I insert @header_linkNumber instead of a number like <%= for element <- MyProject.PageView.Recursion.buildElements(2),1) do %>

I've already tried to use @MyProject.ModuleView.header_linkNumber instead but then I get this error:

cannot set attribute @__aliases__ inside function/macro

Upvotes: 0

Views: 614

Answers (1)

Gazler
Gazler

Reputation: 84180

You are getting "bad argument in arithmetic expression" as you are subtracting an integer from a string:

iex> "3" - 1 
** (ArithmeticError) bad argument in arithmetic expression
    :erlang.-("3", 1)

Change:

header_linkNumber: "3"

To:

header_linkNumber: 2

As an interesting side note, you can actually compare strings to integers:

iex> "3" <= 1
false

You should be aware of this as it could cause unexpected errors if you are using strings instead of integers somewhere else.

The order (from http://elixir-lang.org/getting-started/basic-operators.html) is:

number < atom < reference < functions < port < pid < tuple < maps < list < bitstring

Upvotes: 1

Related Questions