djangodjango-i18ndjango-sites

Different translations for different sites


I am building a directory engine with Django. It will be used on different domains, such as houses.com and games.com etc.

There's a button on the header, which is 'Add Item' which redirects to item creation page. It's wrapped with {% trans %} tag. But I want translation of that button to be "Add your house" on houses.com and "Add Your Game" on games.com.

What is best practice for doing that?

I was expecting to find a solution for that.


Solution

  • You add a contextual marker [Django-doc]. Indeed, we can for example have:

    {% translate "Add item" context site_name %}

    and in the translation file (.po):

    msgctxt "houses.com"
    msgid "Add item"
    msgstr "Add house"
    
    msgctxt "games.com"
    msgid "Add item"
    msgstr "Add game"

    Now the only problem is how to onject a site_name variable in all templates? We can do this with a context processor [Django-doc]. We can define such context processor like:

    # some_app/context_processors.py
    
    from django.conf import settings
    
    
    def with_site_name(request):
        return {'site_name': getattr(settings, 'SITE_NAME', None)}

    then we configure the context processor, and add a SITE_NAME in settings.py:

    # settings.py
    
    # …
    
    SITE_NAME = 'games.com'
    
    # …
    
    TEMPLATES = [
        {
            # …
            'OPTIONS': {
                'context_processors': [
                    'some_app.context_processors.with_site_name'
                ],
            },
        },
    ]
    
    # …