Translation¶
RapidSMS uses Django’s internationalization (i18n) architecture to allow you to make your project or application translatable. This documentation assumes you’re already familiar with this architecture. If you’re not, we recommend reviewing Django’s translation documentation before proceeding.
This page will start with a brief review of Django translation, then move on to RapidSMS translation.
Introduction¶
You can specify a translation string by using the function ugettext
. The
convention is to import this as a shorter alias, _, to save typing. In this
example, the text "Welcome to RapidSMS."
is marked as a translation string:
from django.utils.translation import ugettext as _
def do_something():
output = _("Welcome to RapidSMS.")
By default, Django will attempt to translate this string based on your
LANGUAGE_CODE
setting.
RapidSMS will not automatically attempt to translate routed messages. This is an intential decision to require application developers to explicity initiate the message translation process. You can use the methods below to translate messages.
Language specification¶
To set a specific language, you can use Django’s translation.override
context manager:
from django.utils import translation
from django.utils.translation import ugettext as _
def do_something():
with translation.override("es"): # Spanish
message1 = _("Welcome to RapidSMS.")
with translation.override("fr"): # French
message2 = _("Welcome to RapidSMS.")
Contact language setting¶
Every RapidSMS Contact
has an associated language
field. This field is
used to specify the contact’s language preference. You can use this field to
send messages in the correct language.
Message responses¶
It’s quite common to use msg.respond()
within your application to respond
to messages. To send a response in the contact’s preferred language, you can
use translation.override
with their language:
from django.utils import translation
from django.utils.translation import ugettext as _
from rapidsms.apps.base import AppBase
class HelloApp(AppBase):
def handle(self, msg):
if msg.text == "hello":
with translation.override(msg.connection.contact.language):
msg.respond(_('hello'))
return True
This example will attempt respond with "hello"
in the contact’s preferred language.
Sending messages¶
To ease translating messages to multiple connections, RapidSMS provides a
utility function, group_connections
, to divide connections into groups by
their contact’s language setting.
This example illustrates how you could attempt to say hello in the correct language(s) without needing to inspect each connection manually:
from django.utils import translation
from django.utils.translation import ugettext as _
from rapidsms.utils import translation as trans_helpers
from rapidsms.router import send
def say_hello_to_everyone():
connections = Connection.objects.all()
for lang, conns in trans_helpers.group_connections(connections):
with translation.override(lang):
send(_('hello'), conns)