2013-09-25 15 views
5

我渲染一些pluralization using the blocktrans tag;這裏的模板文件中的相關片段:如何在{%blocktrans%}和{%plural%}標記之間保留空白而不會導致msgfmt錯誤?

{% 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,它編譯得很好。

但是,我的問題是如何保持第一個模板語法,並仍然能夠編譯消息,因爲它大大提高了模板文件中代碼的可讀性。

+0

您是否嘗試過使用['{%spaceless%}'標籤](https://docs.djangoproject.com/en/1.10/ref/templates/builtins/#spaceless)? – guival

回答

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

0

我相信使用{% spaceless %} tag應該可以解決問題。它所做的是刪除其開始和結束之間的任何空格(和行跳轉)。我已經測試過這個,但不使用複數,但它應該工作。

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