0

我有一个 HTML 模板,我需要重复该模板,但使用一组数据中的不同变量。

如果我向您展示我当前的代码,将会更好地解释:

def getBlueWidgets(request):
    widgets = Widget.objects.filter(colour='blue')
    html = generateHtml(widgets)
    return HttpResponse(json.dumps(html), mimetype="application/json")

def generateHtml(widgets):
    html = ''
    for widget in widgets:
        html += '<div class="widget">'
        html += '<div class="title">'
        html += widget.title
        html += '</div></div>'
    return html

getBlueWidgets()通过 AJAX 调用,然后使用 JS 将 HTML 添加到文档中。这很好用,但不是很整洁,而且很难维护我的小部件 HTML 代码。有没有办法可以将我的小部件模板添加到 .html 文件中,以某种方式指定变量应该在哪里,并将其导入到 .html 文件中generateHtml()

谢谢!

4

1 回答 1

1

当然。您可以使用render_to_string

from django.template.loader import render_to_string

def getBlueWidgets(request):
    widgets = Widget.objects.filter(colour='blue')
    html = render_to_string('widgets.html', {'widgets': widgets})
    return HttpResponse(json.dumps(html), mimetype="application/json")

# widgets.html
{% for widget in widgets %}
    <div class="widget">
        <div class="title">{{ widget.title }}</div>
    </div>
{% endfor %}
于 2013-10-16T04:03:43.263 回答