gpt4 book ai didi

Django i18n 用 html 翻译文本

转载 作者:行者123 更新时间:2023-12-02 07:03:43 24 4
gpt4 key购买 nike

如何处理翻译中的 HTML?我想翻译带有 HTML 的句子。例如这样一个字符串([login] 是一个链接):

Please [login] to view your profile.

我不想让我的翻译人员因为翻译带有 html 的文本而烦恼。另一方面,我不想像 this question 中建议的那样在我的 View 中创建所有链接。 。因此,理想情况下,我希望纯模板解决方案能够灵活地制作 HTML,同时允许翻译人员仅使用文本字符串。

例如,此伪代码实现了这些要求:

{% render as login_html %}
<a href="{{ url 'login' }}?next={{ request.path|urlencode }}">
{% trans "Login" %}
</a>
{% endrender %}

{% blocktrans with login=login_html %}
Please {{ login }} to view your profile.
{% endblocktrans %}

首先,登录 HTML 被渲染并存储为 login_url。然后在我的 blocktrans 中,我可以简单地使用 {{ login }} 来提供渲染的登录 HTML。是否有(类似)解决此问题的方法,或者是否需要自定义模板标签?

最佳答案

我创建了一个通用 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 ""

关于Django i18n 用 html 翻译文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14377884/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com