How To - render a string as a template in django

i've been wondering about how i could render a template just by passing a made-inside-view string so that i woudn't have the need to create an html file. I read the Django Docs, but i couldn't find an explanation on this, as far as seen all was about giving the template path string, (also i tried a few lines, but got nothing).

Please, have this as an example:

from django.shortcuts import render
def my_view(request):
    arbitrary_string_as_template = """
        <form action="" method="POST">
        {% csrf_token %}
        <label for="">Username</label>
        <input type="text" name="username">
        <label for="">Password</label>
        <input type="password" name="password">
        <button type="submit">
            submit
        </button>
        </form>
    """
    return render(request, arbitrary_string_as_template, {})

So if this can be done... then i think it would have in its way a good potential, since it gains in terms of versatility..and btw..

#I'm New to Django

Thanks for your attention

Upvotes: 5

Views: 2877

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477676

You can construct a Template object [Django-doc] with the template string, and then .render(…) [Django-doc] it:

from django.http import HttpResponse
from django.template import Template, RequestContext

def my_view(request):
    arbitrary_string_as_template = """
        <form action="" method="POST">
        {% csrf_token %}
        <label for="">Username</label>
        <input type="text" name="username">
        <label for="">Password</label>
        <input type="password" name="password">
        <button type="submit">
            submit
        </button>
        </form>
    """
    template = Template(arbitrary_string_as_template)
    context = RequestContext(request)
    return HttpResponse(template.render(context))

If however the content is static, I would advise to use a file. It makes it easier to separate concerns, and write clean files that each focus on a specific part.

Upvotes: 7

Related Questions