简体   繁体   English

Django:将模板包含到视图中

[英]Django: include template into view

I have a table created with django-tables2 . 我有一个用django-tables2创建的表。 I created a custom column where, given the id, alot of information is loaded and shown. 我创建了一个自定义列,在给定ID的情况下,将加载并显示大量信息。 I created a render method for that column and it works fine. 我为该列创建了一个render方法,它工作正常。 But now, a lot of html sourcecode is in my views.py. 但是现在,我的views.py中有很多html源代码。

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. 我想做的就是将所有代码放入一个html文件中,为每一行加载该文件,并用相应的值填充它。 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. 我想为该表单创建一个模板,包括它,然后插入值,就像在其他页面上所做的一样。

You can use render_to_string : 您可以使用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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM