我创建了一个通用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 ""
#, python-format
msgid "Please %(login_url)s for more information."
msgstr ""