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

前端 未结 2 1135
抹茶落季
抹茶落季 2021-02-06 23:51

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.

相关标签:
2条回答
  • 2021-02-07 00:37

    The selected answer doesn't work.

    Try with this :

    <%= if Map.has_key?(assigns, :company) do %>
      <%= Logo.url({@company.logo, @company}, :thumb) %>
    <% end %>
    
    0 讨论(0)
  • 2021-02-07 00:48

    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] %>
    
    0 讨论(0)
提交回复
热议问题