且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Django:如何在模板中包含视图

更新时间:2023-01-09 08:27:57

需要使用的是 Django自定义模板标签。你可以简单地在你的模板中传递一个变量,然后让它决定在当前模板中插入哪个视图和模板。

What you are going to need to use is a Django Custom Template Tag. You could simply pass a variable to it in your template, then have it decide which view and template to insert in your current template.

一个例子:

您的自定义模板标签(rend_item.py)

Your Custom Template Tag (rend_item.py)

def return_template(item):
    template = 'null'

    context = {
            #Dictionary of things to pass back

    }
    #if statements that choose what 'template' should be
    if item == 5:
        template = 'item5.html'
    else:
        template = 'default.html'

    #render the template
    return render_to_string(template, context)

模板

 {# Make sure you load the py file where your template tag is located at the top #}
 {% load rend_item %}

      {% for item in cart %}

         {{ item|return_template }}         

      {% endfor %}