0

I have a HTML template that I need to be repeated but with different variables from a set of data.

It will be better explained if I show you my current code:

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

I call getBlueWidgets() via AJAX, then add the HTML to the document with JS. This works fine but isn't very neat and it makes it hard to maintain my widget HTML code. Is there a way I can add my widget template to a .html file, somehow specifying where the variables should be, and import it into generateHtml()?

Thanks!

1 Answer 1

1

Sure. You can use 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 %}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.