【问题标题】:Iteration of Hash: JekyII哈希迭代:JekyII
【发布时间】:2017-03-31 11:02:35
【问题描述】:

您好,我正在尝试提取此内容("Polk County", "short_name" => "Polk County") 在这个哈希的第三行,但我似乎只能得到“波尔克县” 这是我当前的代码:

{% for county_hash in location.address_components %}
 {% for county in county_hash %}
  {{ county.long_name }}
 {% endfor %}
{% endfor %}

{
"0" => {
    "long_name" => "426", "short_name" => "426", "types" => ["street_number"]
}, "1" => {
    "long_name" => "Swanee Drive", "short_name" => "Swanee Dr", "types" => ["route"]
}, "2" => {
    "long_name" => "Livingston", "short_name" => "Livingston", "types" => ["locality", "political"]
}, "3" => {
    "long_name" => "Polk County", "short_name" => "Polk County", "types" => ["administrative_area_level_2", "political"]
}, "4" => {
    "long_name" => "Texas", "short_name" => "TX", "types" => ["administrative_area_level_1", "political"]
}, "5" => {
    "long_name" => "United States", "short_name" => "US", "types" => ["country", "political"]
}, "6" => {
    "long_name" => "77351", "short_name" => "77351", "types" => ["postal_code"]
}, "7" => {
    "long_name" => "8238", "short_name" => "8238", "types" => ["postal_code_suffix"]
}

}

【问题讨论】:

  • 位置文件是什么样的?
  • 它将显示LocationDrop方法,该方法能够显示地址,州邮政等
  • 使用上面的迭代代码会给我这个结果'426 Swanee Drive Livingston Polk County Texas United States 77351 8238',但我只需要“Polk County”
  • 有缺失的信息完全理解问题,你应该发布相关文件内容stackoverflow.com/help/mcve

标签: for-loop iteration jekyll shopify liquid


【解决方案1】:

虽然我不清楚你到底想在这里问什么,但下面的代码

{% for county_hash in location.address_components %}
  {% for county in county_hash %}
    {{ county.long_name }}
  {% endfor %}
{% endfor %}

将return 是所有long_names 的字符串,即426 Swanee Drive Livingston Polk County Texas United States 77351 8238,就像您在cmets 中提到的那样。


如果您只需要获取Polk County,则必须使用where 过滤器:

{% for county_hash in location.address_components %}
  {% for county in county_hash %}
    {{ county.long_name | where: "shortname", "Polk County" }}
  {% endfor %}
{% endfor %}

【讨论】:

  • 您好,我认为这会起作用,但是“Polky”这个词总是会根据位置而变化。除了“县”这个词。我想得到这个的原因是显示我网站上的列表所在的县。
  • 是否有一个“if”语句可以用来检查它是否有“县”,然后将其分配给一个变量,以便我可以使用它来显示县? {{county.thisCounty}}
  • "The reason I want to get this is to display the county where the listings in my website is located." --- Ben --- 你能用几个示例场景更新这个问题吗?谢谢
【解决方案2】:

感谢您的帮助, 这种方法对我有用。

{% for county_hash in location.address_components %}
  {% for county in county_hash %}
    {% if county.long_name contains 'County' %}
     {{ county.long_name }}
    {% endif %}
  {% endfor %}
{% endfor %}

breadcrumbs

【讨论】:

    猜你喜欢
    • 2011-02-28
    • 2014-12-15
    • 2017-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 2012-12-27
    相关资源
    最近更新 更多