【问题标题】:Django templates - pass data outside for loopDjango 模板 - 在 for 循环外传递数据
【发布时间】:2021-09-05 22:22:33
【问题描述】:

我有一个用户表,一个表数据是一个打开模式的按钮,我在模板中包含了带有include 标记的模式。如何将用户从单击按钮的行传递到包含标签?

{% for user in users %}
<tr>
 <td>
   <button class="btn btn-lg device-select-button">
          <span>Select Device</span>
   </button>
 </td>
</tr>
{% endfor %}

{% include 'app/admin/users/device_select_modal.html' user={{add here user}} %}

在其他实现中,我为每一行生成了一个模态,它工作但很慢,所以我想重新实现它

【问题讨论】:

  • 我认为您需要 JavaScript 才能做到这一点。 AFAIk 模板仅在您加载页面时构建一次,无法告诉它等待用户点击。另请参阅this question

标签: python html django django-templates


【解决方案1】:

一种方法可能是将您想要传递给模式的所需数据存储为html data attribute

<button data-id={{ user.id }} data-name="{{ user.name }}" class="btn btn-lg device-select-button">

并且在您的模态实现中,您可以使用带有一些 javascript 的按钮的 onclick 属性传递数据。

<button onclick="yourFunctionThatOpensModal(this.getAttribute('data-name'), this.getAttribute('data-id'))"  data-id={{ user.id }} data-name="{{ user.name }}" class="btn btn-lg device-select-button">

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-10
    • 2015-03-21
    • 1970-01-01
    • 2010-11-09
    相关资源
    最近更新 更多