博客五部曲之一 - 简单博客


1280 浏览 5 years, 4 months

15 模板上下文

版权声明: 转载请注明出处 http://www.codingsoho.com/

我们希望能够灵活的渲染模板内容,可以通过context传递相关信息到页面。Context是一个字典变量。

如果我们修改下面两个函数,在context里设置title

def post_detail(request):
    # return HttpResponse("<h1>Detail</h1>")
    context = {
        "title" : "detail"
    }
    return render(request, "index.html",context)   

def post_list(request):
    # return HttpResponse("<h1>List</h1>")     
    context = {
        "title" : "list"
    }
    return render(request, "index.html",context)   

同时,在模板里使用{{title}}来渲染内容。

<body>
    <h1>{{title}} is working!</h1>
</body>

对应显示的内容就会是 detail is working和list is working,我们可以通过修改参数内容,灵活的显示页面,例如可以根据用户是否授权显示不同的内容。

def post_list(request):
    if request.user.is_authenticated()  :
        context = {
            "title" : "my user list"
        }
    else:
        context = {
            "title" : "list"
        }

    return render(request, "index.html",context)