2015-01-11 39 views
1

我有以下的HTML文件template.html:Django的render_to_string行爲

{% load i18n %} 
<p>{% blocktrans %}You have following email: {{ request.user.email }}.{% endblocktrans %}</p> 

現在蟒蛇:

if request.user is not None and request.user.is_authenticated(): 
    text = render_to_string('template.html', context_instance=RequestContext(request))) 

但在模板request.user.email是空的。即使我寫{{ user.email }},它仍然是空的。 如何呈現用戶並正確調用其方法? 例如,{{ request.user.get_short_name }}也不起作用。

UPDATE: 問題同{% blocktrans %}

<p>You have following email: {{ request.user.email }}.</p> 

誰能知道爲什麼? 我還沒有翻譯訊息,但我認爲它會呈現原樣。

+0

檢查'django.core.context_processors.request'是在'TEMPLATE_CONTEXT_PROCESSORS'設置(它不是默認)https://docs.djangoproject.com/en/1.7/ref/templates/api/#subclassing-context-requestcontext'django.contrib.auth.context_processors.auth'默認情況下應該使'user.email'可能 – Anentropic

+0

這些處理器都存在。 –

回答

4

如記錄,你不能直接使用模板表達式{% blocktrans %}裏面,只有變量:

要翻譯模板表達式 - 說,訪問對象屬性 或使用模板過濾器 - 你需要綁定表達爲在變換塊中使用的本地變量 。例子:

{% blocktrans with amount=article.price %} 
That will cost $ {{ amount }}. 
{% endblocktrans %} 

CF https://docs.djangoproject.com/en/1.7/topics/i18n/translation/#blocktrans-template-tag

所以你的模板代碼應該是這樣的:

{% load i18n %} 
<p> 
{% blocktrans with email=request.user.email %} 
You have following email: {{ email }}. 
{% endblocktrans %} 
</p>