phpcakephpemail-templatescakeemail

Substitute variables of a template body email from database by specific information in CakePHP


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?


Solution

  • 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.