I would like to keep an email's template internationalized. I'm using Pyramid 1.4 and Chameleon by default.

I have tried by using a TranslationString directly as the body of a PageTextTemplate:

    default_email_body=r"""
Hello${salutation}${letter_comma}

... full text with several ${data.attributes} ...

Cordialment,
${sender.name}."""

    email_body_template = PageTextTemplate(_('proposed-email-body',
                                             default_email_body,
                                             mapping=params))
    email_body = email_body_template.render()

But email_body gets assigned the msgid instead of the default value, and when I do python setup.py extract_messages the default text is not automatically inserted.

Do I need to do something special to connect my translation domain?

Is there a better way to accomplish this?

A little bit of context

My real world requirement is to create an email from a couple of objects. The user navigates to a page and that page, besides returning a normal HTML page, creates an email that text is automatically sent to a reviewer which either resends it to the client or rejects it. There are two possible requirements for i18n for the email text in this case:

  1. using the language of the of the user of the site,
  2. or using the language of the recipient (the client)

We're opting so far to the 1st, and if time allows it and clients push it, do the 2nd option.

The docs on pyramid for i18n with chameleon refer only to the ZPT templates and not the TXT templates. But our email text is plain text.

So there's a gap in the docs of how to do i18n for plain text templates.

Any ideas?

有帮助吗?

解决方案

Most of these issues can be solved by understanding Pyramid's i18n docs.

A couple things. First, the Chameleon environment needs to have a localizer configured. Pyramid does this for you when you use the default Chameleon setup by calling render('templates/my_email.pt', opts, request=request). If you are using Chameleon's API directly, I do not think the localizer will be found. Also, you'll need a locale negotiator to determine what locale the localizer should be using. There is a default negotiator, but if you are doing this outside of a request, the locale for the user may not be properly configured.

Anyway, my recommendation is to stick to using Pyramid's renderers instead of using Chameleon directly because you lose a lot of the useful configuration Pyramid does for you in this area.

If you cannot use one of Pyramid's renderers for some reason, the i18n docs I linked show how the underlying system works. You need a localizer. Pyramid uses gettext. You then create a TranslationString instance and invoke result = localizer.translate(ts). This is all happening behind the scenes using the default renderers.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top