如果你創建一個 Template 對象,你可以用 context 來傳遞數據給它。 一個context是一系列變量和它們值的集合。
context在Django里表現為 Context 類,在django.template 模塊里。 她的構造函數帶有一個可選的參數:
一個字典映射變量和它們的值。 調用 Template 對象 的 render() 方法並傳遞context來填充模板
e.g:
>>> from django.template import Context, Template >>> t = Template('My name is {{ name }}.') >>> c = Context({'name': 'Stephane'}) >>> t.render(c) u'My name is Stephane.'
我們必須指出的一點是,t.render(c)返回的值是一個Unicode對象,不是普通的Python字符串。
你可以通過字符串前的u來區分。 在框架中,Django會一直使用Unicode對象而不是普通的字符串
所以以上內容更好的講解了以下知識
context = Context({
'to': phone,
'content': mark_safe(text)
})
resp = requests.post(sms_profile.url,data=json.loads(DjangoTemplate(sms_profile.params).render(context))) #短信網關對象參數
該功能可用於ckeditor占位符的渲染,如上就是將context中的文本替換成短信網關的url地址