【问题标题】:Nesting a hyperlink in a table cell using jinja使用 jinja 在表格单元格中嵌套超链接
【发布时间】:2021-07-02 16:42:54
【问题描述】:

我的 HTML 表格有 5 列,我正在使用 jinja 根据数据量动态呈现列的数量。我想在每行的第 5 列中嵌套一个超链接。

from flask import Flask,render_template
from time import time as t
app = Flask(__name__)
@app.route('/offers')
def offers():
    data = ( 
           ("user1","btc","ltc",t(),"127.0.0.1:5000/offer/abcd"),
           ("user2","xrp","xmr",t(),"127.0.0.1:5000/offer/efgh"),
           ("user3","bch","ltc",t(),"127.0.0.1:5000/offer/hijk")
           )
    return render_template("offers.html", data = data)

HTML:

<html>
<body>
    <table class="GeneratedTable">
        <thead>
          <tr>
            <th>Name</th>
            <th>Have</th>
            <th>Want</th>
            <th>Created</th>
            <th>Link</Link></th>
          </tr>
        </thead>
        <tbody>
          {% for row in data %}
          <tr>
          {% for cell in row %}
            <td>{{cell}}
            </td>
          {% endfor %}
        </tr>
          {% endfor %}
        </tbody>
</body>
</html>

这将创建表格,但链接 (127.0.0.1:5000/offers/xxxx) 不会是超链接。如何使用数据集提供的链接仅将最后一列设为超链接?谢谢。

【问题讨论】:

  • 您可以通过向 ;link 添加标签来更改数据本身。 &lt;a href="127.0.0.1:5000/offer/abcd"&gt;127.0.0.1:5000/offer/abcd&lt;/a&gt; 等等然后用安全过滤器在 jinja 中使用它。 {{细胞|安全}}

标签: python html flask jinja2


【解决方案1】:

Jinja 默认不识别 URL。您仍然需要手动格式化它。有两种方法可以做到这一点。

  1. 您可以准备HTML格式的数据,例如
data = ( 
       ("user1","btc","ltc",t(),"<a href=xxx>127.0.0.1:5000/offer/abcd</a>"),
       ("user2","xrp","xmr",t(),"127.0.0.1:5000/offer/efgh"),
       ("user3","bch","ltc",t(),"127.0.0.1:5000/offer/hijk")
       )
  1. 或者您可以将其格式化为 jinja 模板,如下所示:

     <tbody>
       {% for row in data %}
       <tr>
    
           {% for cell in row %}
           <td>
    
               {% if loop.index0 != 4 %}
                   {{cell}}
               {% else %}
                   <a href={{ cell }}>{{ cell }}</a>
               {% endif %}
    
           </td>
           {% endfor %}
    
       </tr>
       {% endfor %}
     </tbody>
    

    这里的关键是使用Jinja语法loop.index0得到row的索引号。

【讨论】:

    猜你喜欢
    • 2021-05-29
    • 2012-03-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-04
    • 1970-01-01
    • 1970-01-01
    • 2018-06-30
    • 1970-01-01
    相关资源
    最近更新 更多