0

我是 python 新手,但是我从 Java 经验中对 MVC 有相当的了解。我认为有以下 python 代码

from django.http import HttpResponse
from django.template.loader import render_to_string

class MyListClass:
    def __init__(self, link, text):
        self.link = link
        self.text = text                

def index(request):
    list1 = MyListClass("hi","_hi_")
    list2 = MyListClass("hello","_hello_")
    bullets = [list1,list2]
    return HttpResponse(render_to_string("nest.html"), {"bullets": bullets})

以及 HTML 模板中的以下代码段

{% for bullet in bullets %}
<h2>
  <a href="{{ bullet.link }}">
    {{ bullet.text }}
  </a>
</h2>
{% endfor %}

但是这些值不会在 html 中发布,而其他静态文本是从 HTML 呈现的。根据文档,传递的对象必须是字典。如果我在某个地方出错,请告诉我。

4

1 回答 1

2

虽然您的代码应该可以工作(假设您将上下文传递给您发现的正确方法),但通常render使用该方法而不是HttpResponse直接构建一个。

from django.shortcuts import render


def index(request):
    bullets = [
        MyListClass("hi", "_hi_"),
        MyListClass("hello", "_hello_")
    ]
    return render(request, "index.html", {"bullets": bullets})
于 2013-06-30T14:43:32.393 回答