如何检查eex中是否存在变量? [英] How do i check if a variable exist, in eex?

查看:93
本文介绍了如何检查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) %>

问题在于,公司变量仅在edit动作中可用,因为新动作上还存在公司,因此我需要检查@company是否已设置.

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.

分配@company在eex模板中不可用.可用的分配:[:action,:changeset]"

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

我尝试过使用is_nil,但存在相同的错误.

I tried with is_nil, but same error.

推荐答案

编辑

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.)

如果使用@companyassigns.company,则将引发错误.但是,如果使用assigns[:company],则如果未设置该值,它将返回nil.

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] %>

这篇关于如何检查eex中是否存在变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆