如何在 rails 应用程序中显示带有 openweather api 的图标

How to display icon with openweather api in rails app

我尝试用 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" %>