【问题标题】:Adding variables in python in html在html中的python中添加变量
【发布时间】:2014-06-13 19:04:02
【问题描述】:

我正在尝试在我的 HTML 中嵌入的 python 中添加变量,它只是打印出添加语句而不是执行它们。这是我的 html 文件中的代码:

<% x = 0 %>
{% for c in UGC %}
  {% if c.doctor_id == doctor.id  %}
    <% {{x}} = {{x}} + {{c.time}} %>
    <h4>Around {{c.time}} minutes.</h4>
    <h4>{{c.comment}}</h4>
    <h4>{{c.submitted_on}}</h4>
    <br>
  {% endif %}
{% endfor %}

{{c.time}} 从数据库中打印出实际时间。 {{c.comment}} 和 {{c.submitted_on}} 分别从数据库中打印出相关的评论和时间戳。但是,当我将 x 初始化为 0,然后尝试在循环的每次迭代中为其添加时间时,会打印出:'' 其中 33 是​​ {{c.time}} 的值循环的那个迭代。

【问题讨论】:

  • 但这是 php 语法。是什么让您认为它可以在 Django 模板中工作?

标签: python html django django-templates


【解决方案1】:

1 - 您正在混合使用 PHP 模板和 Django 模板。

2 - 如果你在这里使用 x 作为临时变量,你可以使用模板的标签。

{% with x = 0 %}

/// you code here

{% endwith %}

3 - 这条线 &lt;% {{x}} = {{x}} + {{c.time}} %&gt; 永远不会工作。您必须编写自己的模板标签才能添加。 {% x|add:c.time %}

【讨论】:

    【解决方案2】:

    一方面(正如 Daniel Roseman 指出的那样),您拥有的代码看起来像 PHP。 Django 模板语言不是 PHP,不应该以这种方式使用。您在模板中拥有的逻辑类型应限于view,模板仅用于呈现输出。

    您的视图可以创建一个字典列表并将该列表传递给您的模板。然后可以这样使用:

    {% for doctor_comment in doctor_comment_list %}
        <h4>Around {{ doctor_comment.time }} minutes.</h4>
        <h4>{{ doctor_comment.comment }}</h4>
        <h4>{{ doctor_comment.submitted_on }}</h4>
    {% endfor %}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-20
      • 1970-01-01
      • 2018-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-28
      相关资源
      最近更新 更多