将 HTML 中的 Python 代码与传入的变量相结合

Combining Python code inside HTML with variables passed in

我正在使用 HTMLBottle (Python) 创建网上商店。我知道如何在HTMLPython之间传递数据,以及如何在HTML中编写Python代码(参考:http://karrigell.sourceforge.net/en/pythoninsidehtml.html)。

我遇到的困难是在从 HTML 传递到 Python 的引用中编写 Python 代码。

我从数据库加载图像,因为我有很多图像。我像这样设置变量 image_name(index) 并将其传递给 HTML

@get('/store')
def showStore():
    images = models.images() # reads from database
    data = ', number_of_images={}'.format(len(images))

    for (id, title, path) in images:
        data += ', image_name{}={}, '.format(id, path)
        data += 'image_title{}={}'.format(id, title)

    return template('store.html' + data)

store.html的相关部分:

<!-- Portfolio Gallery Grid -->

<div class="row">
    <% for i in range(1, number_of_images+1): %>
      <div class="column">
        <div class="content">
          <img src="static/images/{{image_name<%i%>}}.jpg">
          <h3> {{image_title<%i%>}} </h3>
        </div>
      </div>
    <% end %>
</div>

由于 Bottle 不是众所周知的:HTML 中的 {{image_title}} 获取从 template (html, variables) 传入的值。块 <% %> 使您可以在其中编写 Python 代码。

当我没有在 HTML 中使用图像属性索引时一切正常,所以 HTMLfor loop 确实有效,问题出在这部分:

{{image_title<%i%>}}

<%i%> 在我看来应该创建一个变量 image_titlei 但显然它不会。

我收到 template not found 错误,可能是因为我传入的变量(来自 .py 文件)在 HTML.

中不存在

我非常想动态地执行此操作而不是对每张图像进行硬编码的原因是我有很多这样的图像并且每张图像都有完整的 table 相关数据我在这里遗漏了因为我将以与图像名称和标题相同的方式检索它。

如果能帮助我在 HTML 中正确组合 Python 和传入的变量,我将不胜感激,因为我真的很想动态地进行

这里有相当多的错误。

您的模板未找到错误实际上与您在该模板中进行的奇怪操作无关。这是因为您在 Python 代码的最后一行调用 template() 时将模板名称与 data 字符串连接起来。我不知道瓶子,但我绝对肯定数据需要成为该函数的第二个参数:

return template('store.html', data)

至于其他的,完全没有必要做你在那里做的任何事情。只需将图像作为 list 传递,然后在模板中遍历该列表。动态变量 总是 一个坏主意,这同样适用于模板和标准 Python 代码。

(尽管请注意,您甚至没有创建任何动态变量;您只有一个字符串,其格式看起来像一组变量赋值。但这并不能使它实际上在任何地方分配任何变量。)