1

Imagine this scenario, I have a table called "message_templates" with the following structure:-

id
subject
body

where the body value is:-

<p>ID: ${PROJECT_ID} </p>
<p>Project's Title: ${PROJECT_TITLE} </p>

What is the best way to substitute theses variables in CakePHP - I know it, CakeEmail has a Configuration parameter called "template" but its not the case, because my template(body column) comes from database. Maybe use preg_replace or sprintf before send?

Somebody could help me?

drmonkeyninja
  • 8,490
  • 4
  • 31
  • 59

1 Answers1

3

You just need to use str_replace and provide an array of tokens and an array of substitutions:-

$body = str_replace(
    [
        '${PROJECT_ID}',
        '${PROJECT_TITLE}'
    ], 
    [
        '1',
        'Foo bar'
    ],
    $data['MessageTemplate']['body']
);

You can then pass $body to CakeEmail and send the email as normal.

drmonkeyninja
  • 8,490
  • 4
  • 31
  • 59
  • Ok. I will try. But sometimes i will not have all tokens. I need to check if token is present on body message or str_replace dont care about it? – Luiz Paulo Camargo Oct 26 '15 at 19:53
  • If the token isn't present in the body message it will just skip over it with no problem. I use an approach much like this for a site I've been developing to allow the client to be able to edit the content of emails sent by the system with tokens for customer details. It works great. – drmonkeyninja Oct 26 '15 at 20:02