开发者

Django Application Layout: Internationalization

What is the best way to store language constants in django project?

For example, we know, that for translation we need to do:

from django.utils.translation import gettext_lazy as _

class MyThing(models.Model):
    name = models.CharField(help_text=_('This is the help text'))

If we have a lot of variants, we can use dictionary like this:

from django.utils.translation import gettext_lazy as _
MYTRANSLATION = { 
    'term1':_('term1'开发者_运维百科), 
    'term2':_('term2'),
    ...
}

So, my question is, where to store dictionary with language constants... Directly in view, in model, in separate file in app folder, in root folder of project, etc... What is the best way? And where do you store your language consts?


I think it really depends. If you have a big public-facing site that you want to translate into N languages, then they aren't constant and will require updates from dedicated translators whenever the content changes. For a project like that, gettext is wholly unsuitable because gettext is to hard for non-technical persons to use. The site will also require a recompile and redeploy to update the translations which are major dealbreakers if the content is to change often. gettext works for desktop applications (kind of, it is still a major pita for translators) but it does not for web sites.

Instead, use https://github.com/ojii/django-nani. Create a table to hold all translatable strings in your templates:

class I18NString(TranslatableModel):
    key = models.SlugField(unique = True)
    translations = TranslatedFields(
        text = models.TextField(),
    )

For each piece of text you need, add it as a row in I18NString. For example, you could add a row with the key "short-introduction-text" and add the English and German versions of the introduction texts there.

Then for each page load, load all translations for the current language:

# For performance, memcached should be used.   
strings = I18NString.objects.language(request.COUNTRY_CODE).all()
trans = dict((s.key, s.text) for s in strings)

Pass the trans dictionary to the template and render the translated strings:

{{ trans.short-introduction-text }}


Where the strings are actually used. Don't make a separate dict containing translations — it's ugly, destroys context (xgettext won't be able to point to the files where strings are used) and basically duplicates functionality of i18n machinery for no reason.

# yes:
def view(request):
    return HttpResponse(_(u'something something'))

# no:
translations = { 'something something': _(u'something something') }
def view(request):
    return HttpResponse(translations['something something'])
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜