django 中的render和render_to_response()和locals()

1. django中的render

context在Django里表現(xiàn)為 Context 類(lèi),在django.template 模塊里。 它的構(gòu)造函數(shù)帶有一個(gè)可選的參數(shù):

一個(gè)字典映射變量和它們的值。 調(diào)用 Template 對(duì)象 的 render() 方法并傳遞context來(lái)填充模板:

>>> from django.template import Context, Template  
>>> t = Template('My name is {{ name }}.')  
>>> c = Context({'name': 'Stephane'})  
>>> t.render(c)  
u'My name is Stephane.'

views.py中:

return render(request, 'blog_add.html', {'blog': blog, 'form': form, 'id': id, 'tag': tag})

2. django中的render_to_response

 return render_to_response('blog_add.html', {'blog': blog, 'form': form, 'id': id, 'tag': tag})

很明顯,如果使用render_to_response就省去了render里傳遞的request。

3. locals()用法:locals()可以直接將函數(shù)中所有的變量全部傳給模板。當(dāng)然這可能會(huì)傳遞一些多余的參數(shù),有點(diǎn)浪費(fèi)內(nèi)存的嫌疑。

return render(request, 'blog_add.html', locals())
return render_to_response('blog_add.html', locals())
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 模板標(biāo)簽除了幾個(gè)常用的,還真心沒(méi)有仔細(xì)了解一下,看到2.0發(fā)布后,翻譯學(xué)習(xí)一下。 本文盡量忠實(shí)原著,畢竟大神的東西...
    海明_fd17閱讀 2,141評(píng)論 0 5
  • 我不介意忍受孤獨(dú),也不害怕日復(fù)一日的堅(jiān)持,會(huì)坦白承認(rèn)自己技不如人,而后虛心學(xué)習(xí)。我都可以,只要能去到想去的地方。 ...
    一個(gè)無(wú)趣的人W閱讀 374評(píng)論 0 0
  • 已經(jīng)同步到gitbook,想閱讀的請(qǐng)轉(zhuǎn)到gitbook: Django 1.10 中文文檔 Writing you...
    leyu閱讀 709評(píng)論 1 1
  • 由于加載模板、填充 context 、將經(jīng)解析的模板結(jié)果返回為 HttpResponse 對(duì)象這一系列操作實(shí)在太常...
    廖馬兒閱讀 15,747評(píng)論 0 4
  • 開(kāi)始在他的身上摸索起來(lái)。阿亮呢喃道“小毅,咳咳,小毅,能不能幫我個(gè)忙”小毅看著阿亮的樣子,不免想到他們一同在警校的...
    漫長(zhǎng)歲月_b799閱讀 341評(píng)論 0 1

友情鏈接更多精彩內(nèi)容