Django render_to_string 行为

Django render_to_string behavior

我有以下 HTML 文件 template.html:

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

现在 python:

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 }} 也不起作用。

更新: 问题出在 {% blocktrans %}

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

有人能告诉我为什么吗? 我还没有翻译消息,但我认为它会按原样呈现。

如文档所述,您不能直接在 {% blocktrans %} 中使用模板表达式,只能使用变量 :

To translate a template expression – say, accessing object attributes or using template filters – you need to bind the expression to a local variable for use within the translation block. Examples:

{% 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>