【问题标题】:How do I use modal to render data dynamically with Python Flask and HTML如何使用 modal 通过 Python Flask 和 HTML 动态呈现数据
【发布时间】:2023-03-19 14:56:02
【问题描述】:

我在网上查了一下,发现我可以使用宏将不同的内容渲染到我的模态。然而,我的代码中缺少一些东西,导致它无法更新,我不确定到底是什么。

@app.route("/candidates")
def candidate_fun():
  mapping={
    "001":"Bangalore",
    "002":"Delhi",
    "003":"Chennai",
    "004": "Mumbai",
    "005":"Kolkata",
    "006":"Hyderabad"
  }
  myclient=pymongo.MongoClient(uri)
  mydb = myclient["codefundo"]
  mycol=mydb['cand_reg']
  result=[]
  for x in mycol.find():
    obj=NewsSearch()
    # import pdb; pdb.set_trace()
    t=dict(x)
    t['a'],t['b'],t['c']=obj.news_candidate(search_term=str(x["First Name"].lower()+" "+x["Last Name"].lower()+ " election"))
    # t['News']=str(a+".  "+b+". "+c)
    result.append(t)
    # result.append({'News':obj.news_candidate(search_term=str(result["First Name"]+" "+result["Last Name"]+" election"))})
  return flask.render_template("candidate.html",result=result,mapping=mapping)

虽然 python 代码并不重要,但我提供它是为了表明我正在传递一个 dict 类型的列表结果。

HTML 神社

<!--MODAL PART-->
{% macro render_modal(a,b,c) -%}
div class="modal-body">
  <p>{{a}}</p>
  <p>{{b}}</p>
   <p>{{c}}</p>
</div>    
 {%- endmacro%}

<!-- Jinja to make a call -->
{% for key in result %}
<div class="col-6">
 <button type="button" class="btn btn-info" data-toggle="modal" data-target="#exampleModalLong">Info</button>
                                    {{render_modal(key['a'],key['b'],key['c'])}}
     <!-- Just to test if the value sent is received {{key['a']}} -->
 </div>
{% endfor %}

它在模式框中为所有正在传递的条目返回相同的数据。我希望它向我显示迭代中每个新键的特定值 - key[a]、key[b]、key[c]。

【问题讨论】:

    标签: python html flask jinja2


    【解决方案1】:

    这里有类似的问题:Passing a row ID in a table to a modal in flask (python)

    您需要在您的模态框上设置一个id,并在您的按钮中引用该特定的id 来识别一个特定的模态框。为了让每个模式呈现不同的输入,您需要为每个按钮模式组设置 不同 ids。

    在您的情况下,除了您的数据条目之外,还为每个关键对象添加一个唯一标识符,例如

    # in the routes
    t['id'] = # unique id identifying the modal
    t['a'] = ...
    t['b'] = ...
    # etc.
    

    然后在调用模态宏的for循环中,以某种方式在buttondata-target属性中包含唯一ID:

    {% for key in result %}
    <div class="col-6">
      <button type="button" data-target="#exampleModalLong{{ key.id }}" class="btn btn-info" data-toggle="modal">
        Info
      </button>
    
      {{ render_modal(key) }}
    
    </div>
    {% endfor %}
    

    对模态divid 使用与data-target 完全相同的名称:

    {% macro render_modal(key) -%}
    <div class="modal-body" id="exampleModalLong{{ key.id }}">
      <p>{{ key.a }}</p>
      <p>{{ key.b }}</p>
      <p>{{ key.c }}</p>
    </div>    
    {%- endmacro%}
    

    请注意,如果您的 for 循环中有很多条目,这会在您的代码中注入大量 HTML。如顶部链接的 Stack Overflow 帖子中所述,您可以考虑仅定义一个模态,并使用 AJAX 更改模态内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-18
      • 2017-12-09
      • 2013-02-05
      • 2021-11-27
      相关资源
      最近更新 更多