如何在不导致msgfmt错误的情况下保留{% blocktrans %}和{% plural %}标记之间的空格?

8

我正在使用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,它会成功编译。

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


你尝试过使用 '{% spaceless %}' 标签 吗? - gdvalderrama
3个回答

7
文档提到了“trimmed”关键字用于blocktrans,引用如下:

For instance, the following {% blocktrans %} tag:

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

will result in the entry "First sentence. Second paragraph." in the PO file, compared to "\n First sentence.\n Second sentence.\n", if the trimmed option had not been specified.


工作并记录在(至少)Django 1.11下 https://docs.djangoproject.com/en/1.11/topics/i18n/translation/#blocktrans-template-tag - jobima

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)。


-2

我相信使用{% spaceless %}标签应该可以解决这个问题。它的作用是删除其开始和结束之间的任何空格(和换行符)。我只测试了不使用复数形式,但它应该可以工作。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接