如何在rails应用程序中使用openweather api显示图标



我尝试用openweather api显示图标。

它在上工作

_else.html.erb
.
.
<div class="tenki">
<h2>Tokyo</h2>
<img src="http://openweathermap.org/img/wn/10d@2x.png">
.
.

但这只是"10d"模式。我想在那个时候展示图标。

所以试试这个。。

static_pages_controller.rb
.
.
.
uri = URI.parse("http://api.openweathermap.org/data/2.5/weather?q=Tokyo&appid=#{ENV['OPEN_WEATHER_API_KEY']}")
json = Net::HTTP.get(uri)
res = JSON.parse(json)
@wind = res['wind']['speed']
@humidity = res['main']['humidity']
@clouds = res['clouds']['all']
@icon = res['weather'][0]['icon']
_else.html.erb
.
.
<div class="tenki">
<h2>Tokyo</h2>
<img src="http://openweathermap.org/img/wn/#{@icon}.png">
.
.

但这行不通。。这不是错误,所以错误代码为none。浏览器只显示一张破损的小图片。

有人修了吗?请教我。

谢谢你读到这篇文章。

您需要使用ERB标记<%= %>,以便解析器实际评估代码。

<img src="http://openweathermap.org/img/wn/<%= @icon %>.png">

正常字符串插值序列#{}在ERB中没有特殊意义,只会按原样输出。

您也可以使用image_tag助手:

<%= image_tag "http://openweathermap.org/img/wn/#{@icon}.png" %>

最新更新