Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i check if a variable exist, in eex?

I'm working on the crud part of a model, to which i've added image support to. Ideally i would like to show the image if you are editing a model, which i would do like this.

<%= Logo.url({@company.logo, @company}, :thumb) %>

The problem is that the company variable is only available in the edit action, as there are yet a company on the new action, so i need to check if the @company is set.

<%= unless @company do %>
  <%= Logo.url({@company.logo, @company}, :thumb) %>
<% end %>

The problem is that this yields the following error.

"assign @company not available in eex template. Available assigns: [:action, :changeset]"

I tried with is_nil, but same error.

like image 840
MartinElvar Avatar asked Sep 05 '15 10:09

MartinElvar


People also ask

How to check if the variable exists?

Answer: Use the typeof operator If you want to check whether a variable has been initialized or defined (i.e. test whether a variable has been declared and assigned a value) you can use the typeof operator.

How do you check if a variable is defined or not in laravel?

You can use the @isset blade directive to check whether the variable is set or not.


2 Answers

EDIT Prior to Phoenix 0.14.0 @company would return nil if it was not set. It was changed to raise so that the assignment would be explicit (explicit over implicit.)


If you use either @company or assigns.company then an error will be raised. However if you use assigns[:company] then it will return nil if the value is not set.

<%= if assigns[:company] do %>
  <%= Logo.url({@company.logo, @company}, :thumb) %>
<% end %>

It is worth noting that if you are using a nested template then you will need to pass this through too:

<h1>New thing</h1>
<%= render "form.html", changeset: @changeset,
                        action: thing_path(@conn, :create),
                        company: assigns[:company] %>
like image 123
Gazler Avatar answered Oct 22 '22 15:10

Gazler


The selected answer doesn't work.

Try with this :

<%= if Map.has_key?(assigns, :company) do %>
  <%= Logo.url({@company.logo, @company}, :thumb) %>
<% end %>
like image 25
kiru Avatar answered Oct 22 '22 16:10

kiru