我如何检查一个变量是否存在,在 eex 中?
How do i check if a variable exist, in eex?
我正在处理模型的原始部分,我已经向其中添加了图像支持。理想情况下,如果您正在编辑模型,我想显示图像,我会这样做。
<%= Logo.url({@company.logo, @company}, :thumb) %>
问题是 company 变量只在编辑操作中可用,因为新操作中还没有公司,所以我需要检查是否设置了@company。
<%= unless @company do %>
<%= Logo.url({@company.logo, @company}, :thumb) %>
<% end %>
问题是这会产生以下错误。
"assign @company not available in eex template. Available assigns: [:action, :changeset]"
我试过 is_nil,但同样的错误。
EDIT 在 Phoenix 0.14.0 之前 @company
如果未设置,则 return 为零。它被更改为 raise 以便赋值是显式的(显式优于隐式。)
如果您使用 @company
或 assigns.company
,则会出现错误。但是,如果您使用 assigns[:company]
那么如果未设置该值,它将 return nil。
<%= if assigns[:company] do %>
<%= Logo.url({@company.logo, @company}, :thumb) %>
<% end %>
值得注意的是,如果您使用的是嵌套模板,那么您也需要通过它:
<h1>New thing</h1>
<%= render "form.html", changeset: @changeset,
action: thing_path(@conn, :create),
company: assigns[:company] %>
所选答案无效。
试试这个:
<%= if Map.has_key?(assigns, :company) do %>
<%= Logo.url({@company.logo, @company}, :thumb) %>
<% end %>
我正在处理模型的原始部分,我已经向其中添加了图像支持。理想情况下,如果您正在编辑模型,我想显示图像,我会这样做。
<%= Logo.url({@company.logo, @company}, :thumb) %>
问题是 company 变量只在编辑操作中可用,因为新操作中还没有公司,所以我需要检查是否设置了@company。
<%= unless @company do %>
<%= Logo.url({@company.logo, @company}, :thumb) %>
<% end %>
问题是这会产生以下错误。
"assign @company not available in eex template. Available assigns: [:action, :changeset]"
我试过 is_nil,但同样的错误。
EDIT 在 Phoenix 0.14.0 之前 @company
如果未设置,则 return 为零。它被更改为 raise 以便赋值是显式的(显式优于隐式。)
如果您使用 @company
或 assigns.company
,则会出现错误。但是,如果您使用 assigns[:company]
那么如果未设置该值,它将 return nil。
<%= if assigns[:company] do %>
<%= Logo.url({@company.logo, @company}, :thumb) %>
<% end %>
值得注意的是,如果您使用的是嵌套模板,那么您也需要通过它:
<h1>New thing</h1>
<%= render "form.html", changeset: @changeset,
action: thing_path(@conn, :create),
company: assigns[:company] %>
所选答案无效。
试试这个:
<%= if Map.has_key?(assigns, :company) do %>
<%= Logo.url({@company.logo, @company}, :thumb) %>
<% end %>