在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 中使用这些变量?