user1406177
user1406177

Reputation: 1370

Django: include template into view

I have a table created with django-tables2. I created a custom column where, given the id, alot of information is loaded and shown. I created a render method for that column and it works fine. But now, a lot of html sourcecode is in my views.py.

What I want to do is put all that code into one html file, load that file for every row and fill it with the corresponding values. I know how to include templates from other template files, but I don't know how to load templates from source code.

Edit:

My source code roughly looks like this, I hope this shows the problem:

class MyTable(django_tables2.Table):
    [...]
    def render_mycolumn(self, value):
        values = [...]

        s = '<form> ... '
        s += '<button ... >'
        # ten line of codes later
        s += '</form>'
        return mark_safe(s)

I would like to create a template for that form, include it and than insert the values, just like that is done with other pages.

Upvotes: 0

Views: 500

Answers (1)

Adrian Ghiuta
Adrian Ghiuta

Reputation: 1619

You can use render_to_string:

from django.template.loader import render_to_string

class MyTable(django_tables2.Table):
    [...]
    def render_mycolumn(self, value):
        values = [...]

        s = render_to_string('path/to/template.html', { 'key': 'value' })
        return mark_safe(s)

Upvotes: 1

Related Questions