【问题标题】:How to (easily) put python variables from Django into html?如何(轻松)将 python 变量从 Django 放入 html?
【发布时间】:2021-09-01 22:01:16
【问题描述】:

在我的views.py 中的一个Django 项目中,我有一些代码:

from django.shortcuts import render
from django.http import HttpResponse
from .models import *

# Create your views here.

products = Product.objects.all()
product_list = list(products)

def displayhome(request):
    return render(request, 'bootstrap/index.html', {'title': product_list[0].title}, {'link': product_list[0].official_path_name})

现在使用这个(非常笨重的)方法,我可以将变量的字符串版本放入 html 中:

{{title}}

例如。但是,这不允许我对变量进行操作,例如如果我通过product_list 发送,我无法收到product_list[0]。我隐约知道使用{% %} 标签而不是{{ }},但我(a)不完全确定它们是如何工作的并且(b)不知道它们有多强大,例如如果您可以像使用普通的 python 文件一样使用它。

例如,我将如何使用来自 python 的变量(比如它是一个值为 4 的整数)来创建可变数量的 html 元素(例如 4 个框)?

如果没有简单的方法在 html 中执行 python,有没有办法将我的 python 变量放入 javascript,然后以某种方式在 html 中使用这些变量?

【问题讨论】:

  • 经验法则:任何过多的逻辑都不应在模板中完成,而应在视图中完成。无论如何 - 访问模板中的属性/值是通过 . 运算符完成的,无论它是什么数据结构,所以你想要的是 product_list.0
  • 阅读 Django 文档中的 Variables。如果要在模板中访问product_list[0],则必须将其写为{{ product_list.0 }}
  • 有没有更简单的方法可以一次将多个变量添加到模板中?

标签: javascript python html django variables


【解决方案1】:

我将这个结构用于我的视图:

def your_view(request):
    myResult = MODEL_NAME.objects.all()

    context = {
            "variable1":[0,1,2,3,4,5,6],
            "variable2":"This is the variable 2",
            "variable3":"This is the variable 3",
            "variable4":myResult
            }
    return render(request, 'your_html.html', context)

你可以像这样访问模板中的变量

<!-- See variables by index   -->
{{ variable1.0 }}
{{ variable1.2 }}

<!-- Iterate over variables -->
{% for x in variable1 %}
      {{ x }}
{% endfor %}

<!-- Variable 2 & 3 -->
{{ variable2 }}
{{ variable3 }}

<!-- Query set result -->
{% for x in variable4 %}
      {{ x.id }}
      {{ x.name }} <!-- and all the other values from your model -->
{% endfor %}

【讨论】:

    猜你喜欢
    • 2011-09-26
    • 1970-01-01
    • 2010-10-02
    • 1970-01-01
    • 2015-05-28
    • 1970-01-01
    • 2018-02-10
    • 2013-11-27
    • 2015-07-11
    相关资源
    最近更新 更多