Changing tags automatically

Asked

Viewed 57 times

2

I am creating a function for sending email via nodemailer, and our have some templates that are for specific cases.

I need a function that once you receive the Welcome template for example, automatically change some fields (tags).

For example, I will send: 'Olá {Nome}, bem vindo!'

I need you to take the value of the database and change, for example: 'Hello {Nome, bem vindo!' > 'Olá João, bem vindo!'

Or login: 'Seu login é {Login}'.

I need you to take Mysql.

(Sample code)

var mailOptions = {
  from: '[email protected]',
  to: '[email protected]',
  subject: 'Testes de envio de e-mail',
  html: '<p>Seu usuário é {Usuario} e senha é {Senha}</p><p>Olá {Nome}, seja bem vindo!'
};
  • 1

    Ever thought of using strings template?

  • If the answer below solved your problem and there was no doubt left, mark it as correct/accepted by clicking on the " " that is next to it, which also marks your question as solved. If you still have any questions or would like further clarification, feel free to comment.

1 answer

1

You can use a function that extracts the parameters and replaces the respective values as the following:

// Substitui na String de texto a assinatura entre "{}" pelo valor no objeto
const repor = (texto, assinatura, valor) => texto.replace(new RegExp(`{${assinatura}}`, 'ig'), valor);

const substituir = (texto, valores) => {
  // Percorre as chaves para gerar o texto substituído
  const conteudo = Object.keys(valores).reduce((acumulador, assinatura) => repor(acumulador, assinatura, valores[assinatura]), texto);

  return conteudo;
};

console.log(substituir('Olá {Nome}, bem vindo!', { Nome: 'José' }));
console.log(substituir('Nome: {Nome}\nIdade: {Idade}', { Nome: 'José', Idade: 42 }));

It is interesting that you do this replacement on the server, so you have control over the version in which the code runs and ensures that there will be support for the features that are used in the implementation of the function.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.