Magento 2 email templates are supposed to be translated sentence by sentence. This post shows how to use the translator directive.
We assume to have the following line in our de_DE.csv
as german translation for example.
Payment Method:,Bezahlmethode:
We can translate the string Payment Method:
embedded in a span
tag for example in our
template with the following code.
<span>{{trans "Payment Method:"}}</span>
Just two opening curly brackets {{
followed by trans
, the string that should be
translated in double or single quotes and two closing curly brackets }}
.
Many templates are sending variables that can be used in translations. A good and simple example is this one line
in the Magento_Sales::email/order_new.html
template.
{{trans "Thank you for your order from %store_name." store_name=$store.getFrontendName()}}
The line in the translation file de_DE.csv
could look like this for example.
Thank you for your order from %store_name,Vielen Dank für Ihre Bestellung bei %store_name
Here a small snipped of PHP that shows how
Magento\Sales\Model\Order\Email\Sender\OrderSender::prepareTemplate
injects variables.
protected function prepareTemplate(Order $order)
{
$transport = [
'order' => $order,
'billing' => $order->getBillingAddress(),
'payment_html' => $this->getPaymentHtml($order),
'store' => $order->getStore(),
'formattedShippingAddress' => $this->getFormattedShippingAddress($order),
'formattedBillingAddress' => $this->getFormattedBillingAddress($order),
];
$transport = new \Magento\Framework\DataObject($transport);
$this->eventManager->dispatch(
'email_order_set_template_vars_before',
['sender' => $this, 'transport' => $transport]
);
$this->templateContainer->setTemplateVars($transport->getData());
parent::prepareTemplate($order);
}
The $order->getStore()
object that is assigned to the key store
is afterwards available as
$store
in the email template.
Clickable links in translations are not really complicated, but the resulting email template can look a little bit
diffuse. Let us assume that we have a translation like this in our translation file de_DE.csv
for
example.
"
and
that every containing double quote is doubled again to ""
in the translation file.
"Forgot your account password? Click <a href=""%reset_url"">here</a> to reset it.","Haben Sie Ihr Passwort vergessen? Klicken Sie <a href=""%reset_url"">hier</a>,um es zurückzusetzen."
Here an example of clickable links in email templates from
Magento_Customer::email/account_new_confirmed.html
.
<p>
{{trans
'Forgot your account password? Click <a href="%reset_url">here</a> to reset it.'
reset_url="$this.getUrl($store,'customer/account/createPassword/',[_query:[id:$customer.id,token:$customer.rp_token],_nosid:1])"
|raw}}
</p>
We use now single quotes around the string and every doubled double quote from the translation file is now a normal double quote. The url is created similar to the normal PHP function of Magento.