【问题标题】:HTTP Change variable and reload SinatraHTTP 更改变量并重新加载 Sinatra
【发布时间】:2020-05-06 16:34:10
【问题描述】:

我正在使用 Sinatra 和 a Hackernews API 我一直在为分页而苦苦挣扎,这个 API 不是用查询参数来做的

因此,对于站点的信息(第 1 页),端点将是这个 https://api.hnpwa.com/v0/news/1.json 和第 2 页是这个https://api.hnpwa.com/v0/news/2.json

我想从 .erb 文件中发送参数来修改它,但我无法

app.rb

helpers do
  def get_page(site, page)
    "https://api.hnpwa.com/v0/#{site}/#{page}.json"
  end
end

get '/' do
  @page = 1
  endpoint = get_page("news", @page)
  @stories = JSON.parse(HTTP.get(endpoint).to_s)
  erb :news
end

news.erb

<table>
    <tbody>
        <% @stories.each_with_index do |story, index| %>
            <tr>
                <td class="post">
                    <div>
                        <a class="index" href="#"><%= index + 1 %>.</a>
                        <a href="<%= story['url'] %>" class="post-title"><%= story['title'] %></a>
                        <span><a class="url" href="<%= story['url'] %>">(<span><%= story['url'].nil? ? '' : story['url'].split('/')[2] %></span>)</a></span>
                    </div>
                    <div class="post-details">
                        <p><%= story['points'] %> points by <%= story['user'] %></p>
                        <p><%= time_since_in_words(story['time']) %> ago</p>
                        <p>| hide |</p>
                        <p><%= story['comments_count'] %> comments</p>
                    </div>
                </td>
            </tr>            
        <%end%>
    </tbody>
</table>
<a class="more" href=<% @page+=1%>>More</p>

我对 Sinatra 和 Ruby 真的很陌生,所以我不知道还能做什么。感谢您的帮助,谢谢!

【问题讨论】:

    标签: ruby http get sinatra


    【解决方案1】:

    您缺少的部分是您的操作需要接收某种参数。

    目前你总是显示第一页:

    get '/' do
      @page = 1
    

    因此,在路径中,您必须以某种方式与操作沟通您想要显示的页面。为此,您使用参数。有两种方法可以做到这一点:

    带查询参数

    get '/' do
      # href should be something like "/?page=2"
      # set the page according to parameters or default to 
      @page = params['page'] || 1
      …
    end
    

    带路径参数

    get '/:page' do
      # href should be something like "/2"
      @page = params['page']
      ...
    end
    

    路径参数不是可选的,因此它不适用于您的用例,因为您需要有两条路由,一条用于/,一条用于/:page。但这说明了如何使用参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-13
      • 1970-01-01
      • 2010-11-17
      相关资源
      最近更新 更多