我已经创建了一个通用的
render
标签来实现这一点:
from classytags.arguments import Argument, Flag
from classytags.core import Options
from classytags.helpers import AsTag
from django import template
from django.utils.safestring import mark_safe
register = template.Library()
class Render(AsTag):
"""
Renders the block contents to be used elsewhere in the template.
Example usage:
{% render as login_url %}
<a href="{% url 'login' %}">{% trans "Login" %}</a>
{% endrender %}
{% blocktrans %}
Please {{ login_url }} for more information.
{% endblocktrans %}
It will automatically strip leading and trailing whitespace, use `nowrap`
to disable this behaviour:
{% render nostrip as varname %} . . . {% endrender %}
"""
options = Options(
Flag('strip', default=True, false_values=['nostrip']),
'as',
Argument('varname', resolve=False, required=True),
blocks=[('endrender', 'nodelist')],
)
def get_value(self, context, nodelist, strip, **kwargs):
value = nodelist.render(context)
if strip:
value = value.strip()
return mark_safe(value)
register.tag(Render)
当与翻译上下文一起使用时(例如
{% trans "Login" context "login_url" %}
),翻译者将能够在不受HTML干扰的情况下对翻译进行更好的控制。
msgctxt "login_url"
msgid "Login"
msgstr ""
msgid "Please %(login_url)s for more information."
msgstr ""
{{ login }}
是一个变量,不需要再次翻译。 - Bouke