6

我正在使用 blocktrans 标签呈现一些复数形式;这是模板文件中的相关片段:

{% blocktrans count choice_count=choice_count %}
  You have {{ choice_count }} choice:
{% plural %}
  You have {{ choice_count }} choices:
{% endblocktrans %}

运行后python manage.py makemessages --all,这是我的相关片段,例如django.po文件en

msgid ""                                                                        
"\n"                                                                            
"  You have %(choice_count)s choice:\n"                                         
msgid_plural ""                                                                 
"\n"                                                                            
"  You have %(choice_count)s choices:\n"                                        
msgstr[0] "You have one choices:"                                               
msgstr[1] "You have %(choice_count)s choice(s):"   

但是当我运行时python manage.py compilemessages,这是我得到的错误消息:

$ ./manage.py compilemessages 
processing file django.po in /home/yiqing/repos/training/site/training/locale/en/LC_MESSAGES
/home/yiqing/repos/training/site/training/locale/en/LC_MESSAGES/django.po:60: `msgid' and `msgstr[0]' entries do not both begin with '\n'
msgfmt: found 4 fatal errors

我知道这是因为模板文件中的换行符/空格,并且我知道如何“绕过”它——当我将模板片段更改为例如:

{% blocktrans count choice_count=choice_count %}You have {{ choice_count }} choice:{% plural %}You have {{ choice_count }} choices:{% endblocktrans %}

然后重新运行makemessages,从消息中删除fuzzy标记,然后重新运行compilemessages,它编译得很好。

但是,我的问题是如何保留第一个模板语法并且仍然能够编译消息,因为它极大地提高了模板文件中代码的可读性。

4

3 回答 3

3

该文档提到了blocktrans的“修剪”关键字,引用:

例如,下面的{% blocktrans %}标签:

{% blocktrans trimmed %}
  First sentence.
  Second paragraph.
{% endblocktrans %}

将导致输入“第一句。第二段”。在 PO 文件中,与"\n First sentence.\n Second sentence.\n"相比,如果未指定trimmed选项。

于 2018-09-16T12:27:39.647 回答
2

您可以做的最简单的事情是匹配输入字符串的格式。在您的示例中,该.po文件如下所示:

msgid ""
"\n"
"  You have %(choice_count)s choice:\n"
msgid_plural ""
"\n"
"  You have %(choice_count)s choices:\n"
msgstr[0] "\nYou have one choices:\n"
msgstr[1] "\nYou have %(choice_count)s choice(s):\n"

该文件编译时没有错误,但是如您所见,它很乏味。

据我所知,目前没有其他解决方法。似乎django-rosetta确实有一个补丁来处理这个确切的事情(参见https://github.com/mbi/django-rosetta/pull/34)。

于 2014-01-16T16:02:30.987 回答
-1

我相信使用{% spaceless %}标签应该可以解决问题。它所做的是删除其开始和结束之间的任何空格(和行跳转)。我只在不使用复数的情况下对此进行了测试,但它应该可以工作。

{% spaceless %}{% blocktrans count choice_count=choice_count %}
  You have {{ choice_count }} choice:
{% plural %}
  You have {{ choice_count }} choices:
{% endblocktrans %}{% endspaceless %}
于 2017-03-07T11:09:28.887 回答