0

django の翻訳に奇妙な問題があり、理解するのに助けが必要です。問題は、毎回翻訳された文字列を取得するのではなく、翻訳された文字列またはデフォルトの文字列をランダムに取得するように見えることです。

複数のページに「アクション」ボタンを配置するためのクラスを作成しました。これらのボタンの多くは再利用可能です。

<a href="something">blabla</a>

シンプルなツールバーを作成して使用できる場合、いくつかのテンプレートに

toolbar.add(tool)

ビューで、すべてのツールをレンダリングするために templatetag を使用するだけです....とにかく。

これは 1 つのツールの例です。

class NewUserGroupButton(MyTool):
    tool_id = 'new-user-group'
    button_label = ugettext(u'Create new user group')
    tool_href = 'new/'
    js = ()

    def render(self):
        s = '<a id="%(tool_id)s" href="%(tool_href)s" class="button blue">%(button_label)s</a>'
        return s % {'tool_id': self.tool_id, 'tool_href': self.tool_href, 'button_label':self.button_label}

ツールは次のようにレンダリングされます。

class ToolbarTools:
    def __init__(self):
        self.tools = []

    def add(self, tool):
        self.tools.append(tool)

    def render(self):
        # Organize tools by weight
        self.tools.sort(key=lambda x: x.weight)

        # Render tools
        output = '<ul id="toolbar" class="clearfix">'

        for tool in self.tools:
            output += '<li id="%s">' % ('tool-'+ tool.tool_id)
            output += tool.render() if tool.renderable else ''
            output += '</li>'

        output += '</ul>'

        # Reset tools container
        self.tools = []

        return mark_safe(output)

文字列を翻訳するためにugettextを使用しています。(u)gettext=lambda s:s または ugettext_lazy を使用すると、関数の選択に対応する翻訳またはプロキシ オブジェクトが得られません。

そして、私が言ったように - ページの残りの部分は正しい言語で書かれていますが、ツールバーのボタンはランダムに翻訳されているか翻訳されていないようです。異なる「ツール」を使用して異なるページ間を移動したり、同じページを数回更新したりしても、問題のある動作は一貫しています。

誰かがこの問題の原因とその修正方法を理解するのを手伝ってくれませんか?

4

2 に答える 2

2

問題が解決しました。

問題自体 (ランダムな翻訳) は、おそらく ugettext の使用が原因でした。しかし同時に、代わりに ugettext_lazy を使用する必要がありました。

したがって、問題は実際には、変換された文字列ではなくプロキシオブジェクトを返す ugettext_lazy に起因していました...そしてそれはこれが原因です:

[引用] 遅延翻訳オブジェクトの操作 ugettext_lazy() 呼び出しの結果は、Python で unicode 文字列 (unicode 型のオブジェクト) を使用する場所ならどこでも使用できます。バイト文字列 (str オブジェクト) が期待される場所で使用しようとすると、ugettext_lazy() オブジェクトは自分自身をバイト文字列に変換する方法を知らないため、期待どおりに動作しません。バイト文字列内で Unicode 文字列を使用することもできないため、これは通常の Python の動作と一致しています。例えば:

This is fine: putting a unicode proxy into a unicode string.
u"Hello %s" % ugettext_lazy("people")
This will not work, since you cannot insert a unicode object
into a bytestring (nor can you insert our unicode proxy there)
"Hello %s" % ugettext_lazy("people")

[/見積もり]

ここから取得: https://docs.djangoproject.com/en/dev/topics/i18n/translation/#working-with-lazy-translation-objects

アラン

于 2012-08-13T11:49:49.343 に答える