【问题标题】:For-loop implementation of a key for an object HTML对象 HTML 的键的 For 循环实现
【发布时间】:2022-01-10 02:20:01
【问题描述】:

我有一个充满天气对象的查询集,我需要循环访问一个自定义数组,以在 Django 应用程序的 HTML 模板中提取每个天气对象中的特定天气指标。

detail.html

<table>
<tr>
   {% for weather_object in weather_objects %}
      {% for variable in variable_list %}  ## variable_list = ['temp', 'humidity']
          <td>{{weather_object.variable}}</td>
      {% endfor  %}

   {% endfor %}
</tr>
</table>

Views.py

context = {'weather_objects': weather_objects,
           'variable_list': variable_list}

return render(
    request,
    'webapp/detail.html',
    context=context
)

可能有更好的方法来做到这一点,但老实说,我真的很难过。为什么我不能遍历变量列表并从weather_object 中提取数据?特别是“weather_object.variable”,它的作用并不存在。

我可以手动做,我可以专门写

<td>{{weather_objects.temp}}</td> 

<td>{{weather_objects.humidity}}</td> 

但我无法在 for 循环中自动执行它。为什么??我已经验证变量列表中的变量是正确的并且应该可以工作。难道是因为变量只是一个字符串替换?

【问题讨论】:

  • 因为{{ weather_object.variable }} 将寻找weather_object.variable(所以一个属性命名 variable)和weather_object['variable'],而不是weather_object.tempweather_object['temp'] 如果'temp' 分配给 variable

标签: python html django for-loop


【解决方案1】:

如果你写:

{{weather_object<strong>.variable</strong> }}

它旨在从weather_object 中获取属性命名 variable,如果失败,它将尝试使用weather_object['variable']。有一个名为variable 的变量这一事实并不重要。这也很不稳定:假设您分配了一个名为humidity = 'temp' 的变量。它很容易破坏应用程序,因为现在所有item.humiditys 突然应该使用item.temp 代替。那将是糟糕的代码设计。

然而模板应该实现业务逻辑:它应该只实现渲染逻辑。视图需要以可访问的方式将数据传递给视图。

例如,您可以为您的weather_objects 构建一个列表列表:

variable_list = ['temp', 'humidity']
weather_data = [
    [getattr(datum, v) for v in variable_list]
    for datum in wheather_objects
  ]
context = {'weather_data': weather_data }

return render(
    request,
    'webapp/detail.html',
    context=context
)

然后将其渲染为:

<table>
  {% for weather_object in weather_data %}
    <tr>
      {% for item in weather_object %}
          <td>{{ item }}</td>
      {% endfor %}
    </tr>
  {% endfor %}
</table>

【讨论】:

  • 谢谢。此解决方案有效,但具有一些意想不到的下游影响,从根本上使系统工作流程难以用作用户和管理者。也许,仅仅因为你可以并不意味着你应该。
猜你喜欢
  • 2021-10-28
  • 2011-01-23
  • 2020-02-08
  • 2020-07-25
  • 1970-01-01
  • 2016-11-22
  • 1970-01-01
  • 2021-09-12
  • 1970-01-01
相关资源
最近更新 更多